Clayton Clayton - 14 days ago 5
C# Question

Error in C# insert statement to sql server

I am trying to pass an insert statement in a c# winform to sql server. I keep getting a syntax error that just doesnt make sense to me "error in syntax near "(". My syntax is perfectly fine, as when I copy and paste into sql server mgmt studio, the code runs perfectly.

Any help would be greatly appreciated!

Thanks!
error

try
{

using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + "," +
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@tbl", intodrop.SelectedText);
cmd.Parameters.AddWithValue("@colname", colnamedrop.SelectedText);
cmd.Parameters.AddWithValue("@values", valuebox.Text);
cmd.Parameters.AddWithValue("@colname2", colnamedrop2.SelectedText);
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
}
}

Answer

Check that SelectedText property returns you right values. Try to use Text property instead:

var cmd = new SqlCommand("INSERT INTO " + intodrop.Text + 
"(" + colnamedrop.Text + ',' + colnamedrop2.Text + ") " 
+ "VALUES" + " (" + valuebox.Text + ");")