Search Chirayu Software Solutions Blog

Wednesday, April 3, 2013

Insert record in database using stored procedure in asp.net

CREATE PROCEDURE [dbo].[AddUser]
(
@FName varchar(50),
@LName varchar(50),
@DateOfBirth datetime,
@City varchar(50),
@State varchar(50)
)
AS
BEGIN

SET NOCOUNT ON;
INSERT INTO UserDetails (FName, LName, DateOfBirth, City, State)
VALUES (@FName, @LName, @DateOfBirth, @City, @State)
END


C# code

 String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;  
 SqlConnection con = new SqlConnection(ConnString);  
 SqlCommand cmd = new SqlCommand();  
 cmd.CommandType = CommandType.StoredProcedure;  
 cmd.CommandText = "AddUser";  
 cmd.Parameters.Add("@FName",SqlDbType.VarChar).Value = txtFName.Text.Trim();  
 cmd.Parameters.Add("@LName", SqlDbType.VarChar).Value = txtLName.Text.Trim();  
 cmd.Parameters.Add("@DateOfBirth", SqlDbType.DateTime).Value = txtDOB.Text.Trim();  
 cmd.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text.Trim();  
 cmd.Parameters.Add("@State", SqlDbType.VarChar).Value = txtState.Text.Trim();  
 cmd.Connection = con;  
 try  
 {  
      con.Open();  
      cmd.ExecuteNonQuery();  
      lblMessage.Text = "Record inserted successfully";  
 }  
 catch (Exception ex)  
 {  
      throw ex;  
 }  
 finally  
 {  
      con.Close();  
      con.Dispose();  
 }  
Post a Comment