cmd.executenonquery() error in c# code example
Example 1: cmd.executenonquery() error in c#
private void SaveBtn_Click(object sender, EventArgs e)
{
SqlConnection Con = new SqlConnection("Data Source=DESKTOP-BSJERV7\\YAKUBMUCK;Initial Catalog=LoginDatabase;Integrated Security=True");
SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[Student]
([FirstName]
,[LastName]
,[MiddleName]
,[Gender]
,[DOB]
,[Address]
,[Form]
,[Contact]
,[Parent]
,[Fee])
VALUES
('" + FirstNameTextBox.Text + "','" + LastNameTextBox.Text + "','" + MiddleNameTextBox.Text + "','" + GendercomboBox.SelectedItem.ToString() + "','" + DOBdateTimePicker.Value.Date + "','" + LComboBox.SelectedItem.ToString()+ "','" + ContactextBox.Text + "', '" + ParentTextBox.Text+ "','" + FeeTextBox.Text + "')");
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();
MessageBox.Show("Save successifully");
}
Example 2: How to solve error in ExecuteNonQuery() in asp.net
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Harry\Documents\Visual Studio 2015\WebSites\WebSite2\App_Data\Database.mdf; Integrated Security = True";
con.Open();
// insert command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText="INSERT INTO firsttb VALUES ( @n , @p ) ";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@n",TextBox1.Text);
cmd.Parameters.AddWithValue("@p", TextBox2.Text);
cmd.ExecuteNonQuery();
con.Close();