Reputation: 6061
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?
Upvotes: 36
Views: 73381
Reputation: 321
If you have assigned the a DataTable to the DataSource of a DataGridView object, you can access the DataRow associated with the DataGridView row using the DataBoundItem property.
System.Windows.Forms.DataGridViewRow dgvRow = this._mainDGV.SelectedRows[0];
System.Windows.Forms.DataGridView dgv = (System.Windows.Forms.DataGridView)sender;
if (dgvRow is not null)
{
if (dgvRow.DataBoundItem != null)
{
System.Data.DataRow row = ((System.Data.DataRowView)dgvRow.DataBoundItem).Row;
if (row is not null)
{
}
}
}
However, DataBoundItem will have a null value, if you have created a new DataGridView row using the DataGridView's built-in functionality.
Upvotes: 0
Reputation: 584
In Visual Studio 2017 .NET 4.5, I had success with
var row = (DataRowView) e.Row.DataItem;
Upvotes: 0
Reputation: 16196
In a DataGridViewRow
is a property called DataBoundItem
of type object.
This will contain a DataRowView
(for certainty you can check this)
Upvotes: 2
Reputation: 802
DataTable table = grdMyGrid.DataSource as DataTable;
DataRow row = table.NewRow();
row = ((DataRowView)grdMyGrid.SelectedRows[0].DataBoundItem).Row;
Upvotes: 11
Reputation: 42095
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.
Upvotes: 61