I'm using a databound Windows Forms DataGridView
. how do I go from a user selected row in the DataGridView
to the DataRow
of the DataTable
that is its source?
4 Answers
DataRow row = ((DataRowView)DataGridViewRow.DataBoundItem).Row
Assuming you've bound an ordinary DataTable
.
MyTypedDataRow row = (MyTypedDataRow)((DataRowView)DataGridViewRow.DataBoundItem).Row
Assuming you've bound a typed datatable.
See the article on MSDN for more information.
-
Thanks. On a related question; how do I type my rows? Nov 30, 2009 at 21:09
-
You need to read this: msdn.microsoft.com/en-us/library/esbykkzb(VS.71).aspx. However, I'd recommend ignoring them and moving onto LINQ to SQL if you haven't already done so: msdn.microsoft.com/en-us/library/bb425822.aspx Nov 30, 2009 at 21:55
-
3Lovely solution! works like a charm, I used in this way: ((dgvAttached.SelectedCells[0].OwningRow.DataBoundItem as DataRowView).Row as DataRow)– MiBolSep 14, 2015 at 17:16
DataTable table = grdMyGrid.DataSource as DataTable;
DataRow row = table.NewRow();
row = ((DataRowView)grdMyGrid.SelectedRows[0].DataBoundItem).Row;
In a DataGridViewRow
is a property called DataBoundItem
of type object.
This will contain a DataRowView
(for certainty you can check this)
In Visual Studio 2017 .NET 4.5, I had success with
var row = (DataRowView) e.Row.DataItem;