Clayton Clayton - 13 days ago 6
C# Question

Error in C# insert statement for SQL Server

I am trying to pass an insert statement in a C# Winforms to SQL Server. I keep getting a syntax error that just doesn't 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 if SelectedText property returns right values. Try to use Text property instead.

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