Monday, May 11, 2009

Insert data through Stored Procedure in ASP.net

Here we will insert firstname in table tbl_test through dbo.insertfirstname Stored Procedure. Below are the steps to implement it.

Step1 : Add this in web.config file
-----appSettings------
add key="cn" value="workstation id=SQL8;packet size=4096;user id=sa;password=amit;data source=USER1;initial catalog=amit; Connection Timeout=120;"
----appSettings------

Step2 : Add with other namespaces
using System.Data.SqlClient;

Step3: Add under partial class
SqlConnection con;
SqlCommand cmd;

Step4: create connection object in page load event
con = new SqlConnection(ConfigurationManager.AppSettings["cn"]);

Step5: execute insertion stored procedure in database query
create procedure dbo.insertfirstname(@firstname varchar(50)) as insert into tbl_test values(@firstname)

Step6: call this code at add button's Onclick event
cmd = new SqlCommand("dbo.insertfirstname", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@firstname", TextBox1.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();

No comments:

Post a Comment