Glory Raj
Glory Raj

Reputation: 17701

Deleting a row in a datagrid view when a button is clicked

I have a form1 and form2 ..

form1: I have a datagridview with a button column. When I click on the button cell for any row the corresponding row values will be transferred to form2. That was working fine.

Form 2: by using setters and getters I have got the values from form1 and I represent the values in textboxes in form 2, and that was fine.

I have a checkbox in form 2. When I click on the check box, I need to remove the row in datagrid view in form 1 (whose row values are transferred to form 2 when I click on the button cell. That row will be deleted from the datagrid view in form1).

How do I fix this?

Upvotes: 0

Views: 6970

Answers (3)

Abrar Ahmad
Abrar Ahmad

Reputation: 165

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
  dataGridView1.Rows.RemoveAt(item.Index);
}

Upvotes: 1

Damith
Damith

Reputation: 63065

If you know how to delete a record from a grid view from the same form, this is easy.

You can follow the same way as in the answer of Stack Overflow question Updating the gridview in one form.

As the event arguments you can pass the record ID.

You can use the RemoveAt method for deleting a record from the grid view.

DataGridView1.Rows.RemoveAt(deleteIndex);

But if you share the datasource and remove it from form 2 you need to bind data again to remove from the grid. (See How to: Implement Property Change Notification on how to update the gridview.)

If you delete it on the form1 and directly from the gridview, you don't need to bind it again.

Upvotes: 2

Waqas
Waqas

Reputation: 6802

When you pass data from Form1 to Form2, also pass the row index. It will help you delete the row easily.

Either mark the DataGridView of Form1 public or pass it as a constructor parameter to Form2 and then call DataGridView1.Rows.RemoveAt(rowIndex); to delete row at the index specified by rowIndex.

Upvotes: 5

Related Questions