简体   繁体   English

单击按钮时在数据网格视图中删除一行

[英]Deleting a row in a datagrid view when a button is clicked

I have a form1 and form2 .. 我有一个form1form2 ..

form1 : I have a datagridview with a button column. form1 :我有一个带按钮列的datagridview。 When I click on the button cell for any row the corresponding row values will be transferred to form2. 当我单击任意行的按钮单元格时,相应的行值将被传输到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. 形式2 :通过使用setter和getter,我从form1获得了值,并在形式2的文本框中表示了这些值,这很好。

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). 我在表单2中有一个复选框。单击该复选框时,我需要在表单1的datagrid视图中删除该行(当我单击按钮单元格时,其行值将传输到表单2。该行将被删除。从form1的datagrid视图中获取。

How do I fix this? 我该如何解决?

When you pass data from Form1 to Form2 , also pass the row index. 当您将数据从Form1传递到Form2 ,还要传递行索引。 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); 将Form1的DataGridView标记为public或将其作为构造函数参数传递给Form2 ,然后调用DataGridView1.Rows.RemoveAt(rowIndex); to delete row at the index specified by rowIndex . 删除rowIndex指定的索引处的row。

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 . 您可以按照与“堆栈溢出”问题的答案中的相同方法进行操作。 以一种形式更新gridview

As the event arguments you can pass the record ID. 您可以传递记录ID作为事件参数。

You can use the RemoveAt method for deleting a record from the grid view. 您可以使用RemoveAt方法从网格视图中删除记录。

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. 但是,如果您共享数据源并将其从表格2中删除,则需要再次绑定数据以从网格中删除。 (See How to: Implement Property Change Notification on how to update the gridview.) (有关如何更新gridview的信息,请参见如何:实施属性更改通知 。)

If you delete it on the form1 and directly from the gridview, you don't need to bind it again. 如果您在form1上直接从gridview中删除它,则无需再次绑定它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM