I have a datagridview that is filled from a database. I filled a datatable and assigned it as the datasource to the datagridview. I want to be able to select a row from the datagridview and hit a delete button and it be deleted from the database. What would be the best way to do this?

Thanks

private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Selected)//check if row is selected
                {
                    using (SqlConnection conn = new SqlConnection(ConnectionString))
                    {
                        SqlCommand com = new SqlCommand("delete_row", conn);//remove row from database
                        com.CommandType = CommandType.StoredProcedure;
                        com.Parameters.Add(new SqlParameter("@id", Convert.ToInt32(row.Cells[0].Value)));//unique id field of the datarow
                        conn.Open();
                        com.ExecuteNonQuery();
                        conn.Close();
                        dt.Rows.RemoveAt(row.Index);//remove row from the datatable that is bound to the gridview.
                    }
                }
            }

Hope this answers your question.

Thanks! That is exactly what I wanted. I appreciate it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.