1
Reply

how to insert a data from datagrid view to mysql

vimal  balasubramanian

vimal balasubramanian

Oct 28 2013 5:58 AM
1.7k
hi,
i have created a database name search, i need to insert datagrid view data to mysql.
while am executing this code am getting an error called ""object reference not set to an instance of an object""
here is my code
private void btnsave_Click(object sender, EventArgs e)
        {
            MySqlConnection con;
            con = new MySqlConnection(strpth);
            try
            {
                con.Open();
                MySqlCommand cmd;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    cmd = con.CreateCommand();
                    string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
                    string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString();
                    string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString();
                    string col4 = dataGridView1.Rows[i].Cells[3].Value.ToString();
                    string col5 = dataGridView1.Rows[i].Cells[4].Value.ToString();
                    cmd.CommandText = "Insert into searchsong values('" + col1 + "','" + col2 + "','" + col3 + "','" + col4 + "','" + col5 + "')";
                    cmd.Parameters.AddWithValue("@File_Name", col1);
                    cmd.Parameters.AddWithValue("@Actor", col2);
                    cmd.Parameters.AddWithValue("@Music_Director", col3);
                    cmd.Parameters.AddWithValue("@Year", col4);
                    cmd.Parameters.AddWithValue("@Path", col5);
                    cmd.ExecuteNonQuery();                  
                }


            }
            catch (Exception ed)
            {
                MessageBox.Show(ed.Message + "\n" + ed.StackTrace);
            }
        }

Answers (1)