0
votes

I have a DataGridView bound to an array of objects.

List<Node> nodes = GetNodeList();

m_grid.DataSource = nodes;

I then handle the SelectionChanged event.

In the handler for the SelectionChanged event I want to access the selected objects.

All I seem to be able to do is access the value for each cell in the grid rather than the overall object associated with the row.

void OnSelectionChanged( object sender, EventArgs e )
{
    foreach ( DataViewGridRow row in m_grid.SelectedRows )
    {
        /* Here I want to be able to access the Node object associated with this row*/
    }
}

I'm sure it must be possible but I just can't figure it out. I could get the row index and then look back into the array but that seems a bit hacky.

2

2 Answers

3
votes

Try this...

DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;
foreach (DataGridViewRow row in rows)
{
   DataRow myRow = (row.DataBoundItem as DataRowView).Row;
   // Do something with your DataRow
}
2
votes

From memory, cell will be DataGridRowView:

var drv = cell as DataGridRowView;
var row = drv.Row as MyDataRowType;

Anyway, use the debugger to find the Type of cell