繁体   English   中英

删除datagridview中的多行

[英]Delete multiple rows in datagridview

我有一个功能可以在 datagridview 中右键单击删除删除单行..

代码:

  private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {

            if (e.Button == MouseButtons.Right)
            {
                var hti = dataGridView1.HitTest(e.X, e.Y);
                if (hti.RowIndex != -1)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[hti.RowIndex].Selected = true;
                }
            }          
    }

    private void DeleteRow_Click(object sender, EventArgs e)
    {
            Int32 rowToDelete = dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);
            if (rowToDelete != -1)
            {
                dataGridView1.Rows.RemoveAt(rowToDelete);
                dataGridView1.ClearSelection();
            }          
    }

但现在我想在选择时删除多行。
首先我不知道为什么我不能选择多行。
其次,我想使用删除按钮并右键单击鼠标删除来删除多个删除。

有人能帮我吗?

编辑:看看你的代码。 您正在根据HitTest方法的结果设置所选行。 DataGridView属性SelectedRows将确定选择了哪些行。 不确定为什么需要执行HitTest ,但也许您还没有完全解释所需的功能。

if (e.Button == MouseButtons.Right)
{
    var hti = dataGridView1.HitTest(e.X, e.Y);
    if (hti.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        dataGridView1.Rows[hti.RowIndex].Selected = true;
    }
}

确保数据网格上的MultiSelect属性设置为true

然后,您可以在您选择的情况下使用SelectedRows属性:

foreach (DataGridViewRow row in DataGridView1.SelectedRows)
{
    DataGridView1.Rows.Remove(row);
}

请注意以下情况:

如果需要删除datagrid中的记录,不要只将rowIndex存储在datagrid中,(而是应该将相应的键存储在DB中):

例如:我想删除数据网格中的第 1 行和第 2 行,我将它们的 rowIndex 存储在数据网格中。 在datagrid中删除第1行后,第2行的数据会上移到第1行,第3行的数据会上移到第2行,因为你是用datagrid的rowIndex来定位要删除的数据,所以,结果:data1 data3 最终会被删除。

            foreach (DataGridViewRow row in dgShow.SelectedRows)
            {
                string id = row.Cells[4].Value.ToString();
                int x = Convert.ToInt16(id);
                var del = context.ServicesPrice.Where(current => current.Id == x).FirstOrDefault();
                context.ServicesPrice.Remove(del);
            }

你可以写而不是 cell[4]: columns id 在你的数据库中。

暂无
暂无

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

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