Click here to Skip to main content
15,891,136 members
Articles / Database Development / SQL Server / SQL Server 2008R2
Tip/Trick

Insert Data Using Stored Procedure in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.77/5 (10 votes)
23 Apr 2014CPOL 62.3K   12   5
How to insert data using stored procedure in ASP.NET

Introduction

This tip is based on the article "Insert data into SQL Server database using stored procedure and data access layer", written by CodeProject user Rajendra Patel. Here I have class file, stored procedure and web form. Using these, we can insert data into database table.

Using the Code

Create a one class file which interacts between stored procedure and web form. Here form data are passed to InsertData function through Object which is created in web form code behind file.

C#
//Code Behind file code of web form 
protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            Class1 cs = new Class1();
            object[] o = new object[4];
            o[0] = txtName.Text.Trim();
            o[1] = txtAdd.Text.Trim();
            o[2] = Convert.ToDateTime(txtbdt.Text.Trim());
            o[3] = txtsal.Text.Trim();
            cs.InsertData(o, "InsertInformation");
            Response.Write("<script>alert('Data Inserted Successfully!')</script>");
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }
    } 
 
// Class File code which interacts both web form and stored Procedure
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// Summary description for Dal
/// </summary>
public class Dal
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString.ToString());
    SqlDataAdapter da;
    SqlCommand cmd;
    DataSet ds;

    public Dal()
    {
        //
        // TODO: Add constructor logic here
        //
    }public void InsertData(object[] o,string str)
    {
        try
        {
            // Get Length of Object pass from View Page
            int a = o.Length;

            // Create Object to get store procedure parameters
            object[] abc = new object[a];

            // Check Connection Open or Close
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            // Start Code to get SQL parameter from Stored Procedure

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = con;
            myCommand.CommandText = str;
            myCommand.CommandType = CommandType.StoredProcedure;


            SqlCommandBuilder.DeriveParameters(myCommand);

            for (int i = 0; i < myCommand.Parameters.Count - 1; i++)
            {
                abc[i] = myCommand.Parameters[i + 1].ParameterName.ToString();
            }

            // End code to get SQL parameter from Stored Procedure

            // Start Code to Insert data into table using Stored Procedure
            cmd = new SqlCommand(str, con);

            for (int i = 0; i < o.Length; i++)
            {
                SqlParameter sp = new SqlParameter();
                sp.ParameterName = abc[i].ToString();
                sp.Value = o[i];
                cmd.Parameters.Add(sp);
            }

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();

            //End Code to Insert data intot table using stored procedure 
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
} 
 
//Stored Procedure by which we can insert data into database
 ALTER PROCEDURE dbo.InsertInformation
    @Name nvarchar(50),
    @Address nvarchar(max),
    @Bdt date,
    @sal nvarchar(50)
AS
    insert into Information (IName,IAddress,Birthdate,Salary) values(@Name,@Address,@Bdt,@sal)
    RETURN 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer TUV SUD South Asia
India India
I am a senior software developer in .net and also Team leader in SKN organization.

Comments and Discussions

 
GeneralHandsFree Pin
Member 1051379919-May-15 1:53
Member 1051379919-May-15 1:53 
Generalcongratulations Pin
pranav p pandya25-Apr-14 1:58
pranav p pandya25-Apr-14 1:58 
QuestionGood Pin
Member 997361424-Apr-14 7:22
Member 997361424-Apr-14 7:22 
QuestionNice! Pin
Volynsky Alex23-Apr-14 8:59
professionalVolynsky Alex23-Apr-14 8:59 
GeneralNice Pin
SOHAM_GANDHI23-Apr-14 3:46
SOHAM_GANDHI23-Apr-14 3:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.