I have a DataGrid containing a small table. Until now, I had a double click handler on this grid which iterated over all rows to find the selected one:
DataTable table = (DataTable)this.dataGrid.DataSource;
int selectedRow = -1;
for (int i=0; i<table.Rows.Count; i++)
if (this.dataGrid.IsSelected(i))
selectedRow = i;
break;
}
if ( selectedRow != -1 ) {
DataRow row = table.Rows[selectedRow];
// More code ...
}
Problem: When the user clicks on a column header and sort the table, table.Rows does not return the right rows. It still contains the unsorted rows.
How can I get the right column?
Edit 1: I have a System.Windows.Forms.DataGrid, not a DataGridView. I don’t know the difference, because I don’t know .Net very much. Can I simply replace DataGrid with DataGridView?
DataGrid (Windows)
Try
DataGrid.GetSelectedDataRowsbelow, whereMyBaseis the name of yourDataGrid.DataGridView
Use the
SelectedRowsproperty. It returns the collection ofDataGridViewRowobjects. Since you know you are binding aDataTable, theDataGridViewRow.DataBoundItemproperty will be aDataRow. Check the above object help topics for examples.References
Differences Between the Windows Forms DataGridView and DataGrid Controls at http://msdn.microsoft.com/en-us/library/ms171628.aspx
DataGridView Class at
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx
DataGrid Class at http://msdn.microsoft.com/en-us/library/system.windows.forms.datagrid.aspx
Excerpts