Call a stored procedure with parameter in c#
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd
variable, and never use it. Here, however, you will use that instead of da.InsertCommand
.
Also, use a using
for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(dc.Con)) { using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text; cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text; con.Open(); cmd.ExecuteNonQuery(); } }}
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con)){ using (SqlCommand cmd = new SqlCommand("SP_ADD", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text); cmd.Parameters.AddWithValue("@LastName", txtlastname.Text); con.Open(); cmd.ExecuteNonQuery(); } }
cmd.Parameters.Add(String parameterName, Object value)
is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason theydeprecated the
cmd.Parameters.Add(String parameterName, Object value)
in favor ofAddWithValue(String parameterName, Object value)
is to give moreclarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(dc.Con)) { using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text; cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text; con.Open(); cmd.ExecuteNonQuery(); } }}