如何从DataGridView中删除选定的行?

7

我有一个DataGridView和一个Button。如果选择了行,我想通过点击按钮来删除它们。我尝试了一些命令,如RemoveAtSelectedRows等,但都没有起作用。我该怎么解决呢?

我尝试了以下代码:

if (dataGridView2.SelectedRows.Count > 0)
{
    DataGridViewSelectedRowCollection rows = dataGridView2.SelectedRows;
    dataGridView2.Rows.RemoveAt(rows);
} 

但 RemoveAt 方法只接受整数。之前我尝试使用所选单元格,但是它会删除所有行,因为始终存在一个单元格被选中。


是的 - 那就是我的意思。对此感到抱歉。 - MKX2015
1
请展示您尝试过的内容,即使它没有起作用。这样我们就知道问题所在,并可以帮助解决它。 - Tim Schmelter
请注意,如果您使用数据源填充了网格,则可能希望更新该源,网格将自动更新。 - Pankaj
这些链接可能会对你有所帮助。 - Rajat_RJT
7个回答

20
如果您只想从 DataGridView 中删除所选行,可以使用以下代码:
foreach (DataGridViewRow row in yourDataGridView.SelectedRows)
{
    yourDataGridView.Rows.RemoveAt(row.Index);
}

你的代码没有起作用是因为你使用了RemoveAt(rows),但是RemoveAt只接受你想要移除的行的索引。你正在向它传递一个DataGridViewSelectedRowCollection。你可以通过上面所示的DataGridViewRow.Index来获取行的索引。


那正是我正在寻找的!谢谢! - MKX2015
如果有帮助,请标记为“答案”。 - Sorrel Vesper
你可能想添加一条注释,解释为什么这个操作不会抛出“无法修改迭代的集合”的错误。 - TaW
@TaW: 我猜SelectedRows方法会创建一个新的、与DataGridView.Rows没有关联的集合,因此在枚举时可以修改它。编辑已确认:http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridView.cs,37d6f20ebb9d623e - Tim Schmelter
有趣。感谢你挖掘出来。ListView也是这样做的。另一方面,我觉得ListBox也是这样做的,但不允许您枚举集合并修改它。 - TaW
@TaW:但是你可以使用ListView.SelectedIndices集合,不是吗? - Tim Schmelter

2
如果您正在使用模型列表,以下代码可能会有所帮助:
foreach (DataGridViewRow row in dataGridViewX.SelectedRows)
{
    var val = (int)row.Cells[0].Value;
    Products.Remove(Products.Find(d => d.ProductId == val));
}
dataGridViewX.DataSource = null;
dataGridViewX.DataSource = Products;

0

你已经接近成功了 - 试试下面的代码片段

if (dataGridView1.SelectedRows.Count > 0) {
    DataGridViewSelectedRowCollection row = dataGridView1.SelectedRows;
    // taking the index of the selected rows and removing/
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
else {  //optional    
    MessageBox.Show("Please select a row");
}

0
你可以使用类似下面的代码:
foreach(DataGridViewRow row in dgv1.SelectedRows)
{
    dgv1.Rows.Remove(row);
}

0
我遇到了这个问题,并没有找到正确的答案。当你删除一行时,如果这一行是集合中的第一行,所有其他行的索引都会改变,你可能会误删其他行。因此,你必须循环直到所选项计数为零,否则你可能会错过其他选定的行。
以下是我的方法:
while (dataGridView1.SelectedRows.Count > 0)
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);

应该使用for循环而不是while循环 for (int i = 0; i < dataGridView1.Rows.Count;i++ ) - Yasser Gersy

0
请尝试这个,希望能有所帮助。 1. 要启用删除功能,请将AutoGenerateDeleteButton设置为true,并在SqlDataSource中指定删除命令。
 DeleteCommand="DELETE From [stores] WHERE [stor_id] = @stor_id"

2. 在这里,我们试图在删除指定行之前显示确认消息。为了做到这一点,我们必须编写一个小的Javascript代码来显示确认消息。

 function isDelete()
  {
    return confirm("Do you want to delete this row ?");
  }

3. 我们必须在删除 LinkButton 的 OnClientClick 事件中调用此 Javascript 函数。

<asp:LinkButton ID="DeleteBtn" runat="server" CommandName="Delete"
OnClientClick="return isDelete();">Delete</asp:LinkButton>

4. 下面的ASP.NET程序演示了如何从Gridview中删除一行,并在删除指定行之前显示确认消息。

Default.aspx /// 页面

![<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        function isDelete()
        {
            return confirm("Do you want to delete this row ?");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
    AllowSorting="True" DataSourceID="SqlDataSource1" AllowPaging="True" DataKeyNames="stor_id" >
        <Columns>
        <asp:BoundField ReadOnly="True" HeaderText="stor_id"
        DataField="stor_id" SortExpression="stor_id"></asp:BoundField>
        <asp:BoundField HeaderText="stor_name" DataField="stor_name"
        SortExpression="stor_name"></asp:BoundField>
        <asp:BoundField HeaderText="stor_address" DataField="stor_address"
        SortExpression="stor_address"></asp:BoundField>
        <asp:BoundField HeaderText="city" DataField="city"
        SortExpression="city"></asp:BoundField>
        <asp:BoundField HeaderText="state" DataField="state"
        SortExpression="state"></asp:BoundField>
        <asp:BoundField HeaderText="zip" DataField="zip"
        SortExpression="zip"></asp:BoundField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="DeleteBtn" runat="server" CommandName="Delete"
                OnClientClick="return isDelete();">Delete
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
    SelectCommand="select * from stores"
    DeleteCommand="DELETE From \[stores\] WHERE \[stor_id\] = @stor_id" >
    <DeleteParameters>
        <asp:Parameter Name="stor_id" Type="String" />
    </DeleteParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>]

这是图片

Check this picture it's might help you


3
这是一个关于WinForms的问题,而不是WebForms。 - Iswanto San

0

你可以通过编程找到你正在尝试选择的行:

dataGridViewX.Rows[0].Selected = true;

然后删除所选行:

dataGridViewX.Rows.RemoveAt(dataGridViewX.SelectedRows[0].Index);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接