How Do I Get the Selected DataRow in a DataGridView?

47,775

Solution 1

I'm not sure how to do it w/o a BindingSource, here is how to do it with one:

var drv = bindingSoure1.Current as DataRowView;
if (drv != null)
  var row = drv.Row as MyRowType;

Solution 2

DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem
DataRow row = currentDataRowView.Row

Solution 3

It is possible by getting following property:

this.dataGridView.SelectedRows

One obtains a collection of type: DataGridViewSelectedRowCollection. It contains items of type: DataGridViewRow.

Then one can get bounditem with ones own type in following way:

DataGridViewSelectedRowCollection list = this.dataGridViewInventoryRecords.SelectedRows;
MyType selectedItem = (MyType)list[0].DataBoundItem; //[0] ---> first item

Solution 4

You should be able to directly cast your selected row into the strongly typed row that was bound to the DataGridView.

Share:
47,775
Damien
Author by

Damien

Updated on July 09, 2022

Comments

  • Damien
    Damien almost 2 years

    I have a DataTable bound to a DataGridView. I have FullRowSelect enabled in the DGV. Is there a way to get the selected row as a DataRow so that I can get strongly typed access to the selected row's values?