views:

293

answers:

2

I'm using a databound WinForms DataGridView; how do I go from a user selected row in the DGV to the DataRow of the DataTable that is its source?

+1  A: 

In a DataGridViewRow is a property called DataBoundItem of type object.

This will contain a DataRowView (for certainty you can check this)

Captain Comic
+1  A: 
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.

Neil Barnwell
Thanks. On a related question; how do I type my rows?
Dan Neely
You need to read this: http://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: http://msdn.microsoft.com/en-us/library/bb425822.aspx
Neil Barnwell