首页 文章

在给定索引的情况下从DataGridView中删除一行

提问于
浏览
2

我的DataGridView是单行选择,还有一个rowEnter事件,每当所选行改变时,我都会得到行索引 .

private void rowEnter(object sender, DataGridViewCellEventArgs e)
    {
        currentRowIndex = e.RowIndex;
    }

当我按下删除按钮时,我使用相同的索引来删除该行

myDataSet.Avaliado.Rows[currentRowIndex].Delete();
            avaliadoTableAdapter.Update(myDataSet.Avaliado);

如果没有对DataGridView中的列进行排序,它可以正常工作,否则会出错 . 应该如何知道数据集中与DataGridView中的rowindex相对应的行索引?

3 回答

  • 2

    每次选择新行时,您都不需要抓取当前行索引 . 尝试这样的事情:

    if (_Grid.SelectedRows.Count <= 0) { return; } // nothing selected
    
    DataGridViewRow dgvRow = _Grid.SelectedRows[0];
    
    // assuming you have a DataTable bound to the DataGridView:
    DataRowView row = (DataRowView)dgvRow.DataBoundItem;
    // now go about deleting the row however you would do that.
    

    如果你有一些其他类型的数据类型绑定到网格的每一行,只需将 DataGridViewRow.DataBoundItem 转换为您的数据类型 .

  • 0

    我通常将该行的主键作为隐藏列(我的约定是使用第一个使用列) .

    然后,我可以让我的持久层继续进行 .

  • 0

    您可以在执行删除时找到当前选定的行:

    if(myDataGridView.SelectedRows.Count > 0)
         currentRowIndex = myDataGridView.SelectedRows[0].Index;
    

相关问题