Question Error when inserting values to DB (SQLServer)

shsh_shah

Member
Joined
Aug 29, 2012
Messages
5
Programming Experience
Beginner
Hello,

Error when inserting values to DB (SQLServer)

Error =
Invalid column name = TaskName and Time


private void submitBtn_Click(object sender, EventArgs e)
{
String insertSQL = "Insert into Time_Allocated (TaskName,Time) VALUES (TaskName,Time) SELECT @@IDENTITY AS EmpID";
try
{
cm = new SqlCommand(insertSQL, cn);
cm.Parameters.AddWithValue("@TaskName", textbox.Text);
cm.Parameters.AddWithValue("@Time", totalTimetxtBox.Text);
cm.ExecuteNonQuery();
cm.Parameters.Clear();
int insertID = Convert.ToInt32(cm.ExecuteScalar());
cm.Dispose();
cm = null;
}
catch (Exception ex)
{ MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}

Thanks,
 
First of all, as you apparently know from your AddWithValue calls, parameters names start with an @, yet you are not starting your parameter names with an @ in your SQL code. That is your first mistake.

Apart from that, your executing your SQL code twice. You call ExecuteNonQuery, which executes it once, and ExecuteScalar, which executes it again. That means that you are inserting two records and discarding the ID of the first. You need to be executing the SQL code only once. That means retrieving the ID via an output parameter.
 
Back
Top Bottom