views:

174

answers:

3

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?

A: 

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.

Johannes Rudolph
A: 

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;
msergeant
its the same value I already have from rowEnter event, isnt it? A row in a DataGridView has a index, a row of data in a dataset has another position that not necessarily corresponds to the the DataGridView. Thats the point.
Ruben Trancoso
Sorry. I thought you meant that you were losing the proper index when the column gets sorted. myDataGridView.SelectedRows[0].DataBoundItem is indeed what you're interested in then.
msergeant
+2  A: 

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.

Yoopergeek
Great, thank you very much. Just a comment. In the wurry you did a mistake. Nothing serious. :)DataRowView row = (DataRowView)dgvRow.DataBoundItem;Only strange thing is that when the last row in the DGV is deleted, the DVG do not select the previous available row.
Ruben Trancoso
Oops! You're correct. The sample piece of code I was looking at for whipping up that sample code involved a BindingList<T> bound to a DataGridView, so there was no intermediary DataRowView. I'll update the example...
Yoopergeek