Osama Jutt Osama Jutt - 3 months ago 9
SQL Question

Finding Error, I am unable to locate it Help me out

i am un-able to locate that error in my code


Error: System.Data.SqlClient.SqlException (0x80131904): Incorrect
syntax near 'Name'.


try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["UserData_DB"].ConnectionString);

string insert = "INSERT INTO UserData(First Name,Last Name,Father Name,CNIC NO,Gender,Religion,Address,City, Cell Number, Email) VALUES (@fName,@lName,@fathName,@cnicNo,@gender,@religion,@address,@city,@cellNumber,@email)";
SqlCommand com = new SqlCommand(insert, con);
com.Parameters.AddWithValue("@fName", TextBoxfName.Text);
com.Parameters.AddWithValue("@lName", TextBoxlName.Text);
com.Parameters.AddWithValue("@fathName", TextBoxFatherName.Text);
com.Parameters.AddWithValue("@cnicNo", TextBoxcnicNo.Text);
com.Parameters.AddWithValue("@gender", RadioButtonList1.SelectedItem.Value.ToString());
com.Parameters.AddWithValue("@religion", RadioButtonList2.SelectedItem.Value.ToString());
com.Parameters.AddWithValue("@address", TextBoxAddress.Text);
com.Parameters.AddWithValue("@city", DropDownList1.SelectedValue.ToString());
com.Parameters.AddWithValue("@cellNumber", TextBoxCellNumber.Text);
com.Parameters.AddWithValue("@email", TextBoxEmail.Text);

con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}

Answer

Your column names in the insert have spaces and if the column names have spaces you need to surround them with square brackets [], like this:

INSERT INTO Names([First Name],[Last Name])VALUES('First Name 1','Last Name 1')

Ideally the column names in SQL shouldn't have spaces, I would recommend renaming them like FirstName,LastName e.t.c