删除dataGridView中的选定行 [英] removing selected rows in dataGridView

查看:81
本文介绍了删除dataGridView中的选定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个dataGridView,其中填充了文件列表。我希望能够通过选择条目(单击它)然后按Delete键来删除其中的一些条目。这是我到目前为止的代码:

I have a dataGridView that I populate with a list of files. I'd like to be able to remove some of those entries by selecting the entry (by clicking it) and then pressing the delete key. Here's the code I have so far:

private void DataGrid_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Delete)
     {
           foreach (DataGridViewRow r in DataGrid.SelectedRows)
           {
                if (!r.IsNewRow)
                {
                    DataGrid.Rows.RemoveAt(r.Index);                        
                }
           }
     }
}

问题在于它将选定的行定义为一次单击的所有行。我想删除所有突出显示的行。换句话说,如果某行未突出显示,则不会被选中。

The problem is that it defines selected rows as all rows that were at one time clicked on. I would like to delete all highlighted rows. In other words, if a row is not highlighted it's not selected.

推荐答案

这应该有效

 private void DataGrid_KeyDown(object sender, KeyEventArgs e)
 {
   if (e.KeyCode == Keys.Delete)
   {
    Int32 selectedRowCount =  DataGrid.Rows.GetRowCount(DataGridViewElementStates.Selected);
    if (selectedRowCount > 0)
     {
        for (int i = 0; i < selectedRowCount; i++)
        {
            DataGrid.Rows.RemoveAt(DataGrid.SelectedRows[0].Index);  
        }
     }
   }
}

这篇关于删除dataGridView中的选定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆