0

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

2
Contributors
2
Replies
5
Views
8 Years
Discussion Span
Last Post by functionalCode
0
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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.