Adnan Hossain Adnan Hossain - 11 months ago 36
SQL Question

"Invalid column name" when trying to insert data into database using SQL

Im trying to insert new values into my database using visual studio and here is my code:

SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = dbconnectionstring;
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Data_ConfigInfo (TypeID, Name, ValidFromDate, ValidToDate, ValidFromSOP, ValidToSOP, Description)" +
"VALUES(@TypeID, @Name, @ValidFromDateTime, @ValidToDateTime, @ValidFromSOP, @ValidToSOP, @Description)";
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
if(Logg.ValidFrom.Equals(null)) {
cmd.Parameters.AddWithValue("@ValidFromDateTime", DBNull.Value);
cmd.Parameters.AddWithValue("@ValidFromDateTime", Logg.ValidFrom);
if (Logg.ValidTo.Equals(null))
cmd.Parameters.AddWithValue("@ValidToDateTime", DBNull.Value);
cmd.Parameters.AddWithValue("@ValidToDateTime", Logg.ValidFrom);
cmd.Parameters.AddWithValue("@ValidFromSOP", Logg.ValidFromSOP);
cmd.Parameters.AddWithValue("@ValidToSOP", Logg.ValidToSOP);
cmd.Parameters.AddWithValue("@Description", Logg.Description);

But at the line cmd.ExecuteNonQuery(); i get the error invalid column name for ValidToDateTime and ValidFromDateTime. Both are datetime variabels. I can't seem to find the error. Any ideas? This is how my datatable looks

Datatable structure

Raj Raj

Your DB table has columns ValidFromDateTime, ValidToDateTime, but your column list in the INSERT statement has ValidFromDate, ValidToDate. Are you sure that it is not a typo when posting here?