I got a question to ask here. Why can’t my data be inserted into my database? I’ve already create a table in SQL Server. Here is my line of code for your reference.
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab(Brand,Model,Plate,Color,Service) Values (@brand,@model,@plate,@color,@year,@service)",conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@brand", Label1.Text);
cmd.Parameters.AddWithValue("@model", Label2.Text);
cmd.Parameters.AddWithValue("@plate", Label3.Text);
cmd.Parameters.AddWithValue("@color", Label4.Text);
cmd.Parameters.AddWithValue("@year", Label5.Text);
cmd.Parameters.AddWithValue("@service", Label6.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
Is there something wrong with my code? Pls help me. Im stuck over here. Thank you.
It looks like you are missing
Yearin your command statement:You are supplying 6 parameters but only 5 columns.
Are you getting an error message? Usually, there will be an error message with some information; it usually looks something like this:
EDIT.
If you are still having problems, the next thing to do is to look at the actual error message. Let’s refactor your code slightly:
If you are seeing no error at all, and that’s what puzzled me initially, then it might actually be because your event handler isn’t wired up; sometimes, the designer will unwire event handlers meaning your click and the actually code become disassociated and never run.
Check you have:
In
InitializeComponentor in the constructor or Load events.