Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a form which has a datagridview with two columns clmCategoary and clmActivity
when i click the save button it should insert the in all the gridview into the db.
but it gives the error message "invalid column name". pls what should i do

C#
private void btnSave_Click(object sender, EventArgs e)
        {
            string StrQuery;
            try
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
                {
                    conn.ConnectionString = "Data Source=MICKY-PC;Initial Catalog=MUCGPROJECT;User ID=sa;Password=mike";
                     using (SqlCommand comm = new SqlCommand())
                       {
                            comm.Connection = conn;
                            conn.Open();
                             for(int i=0; i< dataGridView1.Rows.Count;i++)
                            {
                                StrQuery = @"INSERT INTO CategorynA VALUES (" + dataGridView1.Rows[i].Cells["clmCategory"].Value + ", " + dataGridView1.Rows[i].Cells["clmActivity"].Value + ");";
                                comm.CommandText = StrQuery;
                                comm.ExecuteNonQuery();
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
Posted

I believe you are missing single quotes in your query
C#
StrQuery = @"INSERT INTO CategorynA VALUES ('" + dataGridView1.Rows[i].Cells["clmCategory"].Value + "', '" + dataGridView1.Rows[i].Cells["clmActivity"].Value + "');";
 
Share this answer
 
Comments
mikeoabban 13-Jul-12 17:38pm    
thanks i never noticed it
[no name] 13-Jul-12 17:42pm    
You're welcome.
but it gives the error message "invalid column name"
It simply means that the insert query formed has an invalid column name.

Simply put a break point before query execution, use DEBUGGER and see what is the formed query:
C#
StrQuery = @"INSERT INTO CategorynA VALUES (" + dataGridView1.Rows[i].Cells["clmCategory"].Value + ", " + dataGridView1.Rows[i].Cells["clmActivity"].Value + ");";

Verify it by directly running in SQL server to see if it is fine. Check the column name set is present in table.
 
Share this answer
 
Hi,

In my opinion you forgot to specify you field names:

example:
StrQuery = @"INSERT INTO [dbo].[CategorynA](Category, Activity) VALUES ('" + dataGridView1.Rows[i].Cells["clmCategory"].Value + "', '" + dataGridView1.Rows[i].Cells["clmActivity"].Value + "');";


Please do not forget to vote if could help...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900