2
votes

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)
    {
        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?

3

3 Answers

2
votes

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.

0
votes

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.

0
votes

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;