开发者

Delete a Row from a DataGridView given its index

My DataGridView is a single line selection and theres a rowEnter Event where I get the line index every time the selected line changes.

    private void rowEnter(object sender, DataGridViewCellEventArgs e)
    {
      开发者_C百科  currentRowIndex = e.RowIndex;
    }

when I press a delete button I use the same index to delete the row

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

it works fine if no column in the DataGridView is sorted, otherwise a get an error. What should be the way to know the row index in the dataset that corresponds to the rowindex from the DataGridView?


You don't need to be grabbing the current row index every time a new row is selected. Try something like this instead:

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.

If you've got some other sort of data type bound to each row of the grid, simply cast the DataGridViewRow.DataBoundItem to whatever your data type is.


I usually have the Primary Key for that row as a hidden column (my convention is using the first using column).

I can then ask my persistence Layer to do the rest.


You can find the currently selected row at the time that you are doing the delete:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜