Introduction
It's a shame that this requires even a short article to explain this - but some things in .NET are missing "practical" short cuts. This article demonstrates how to obtain the row in a DataTable
that the currently selected row in a DataGrid
is linked to.
Warning: Topic is to be considered to be of beginner level. Please no e-mail from intermediate or advanced developers about this article being "too basic". There are still many beginning programmers looking for beginner level articles - in fact once upon a time we were all there and complaining that all the articles were "too advanced".
Code
This is the basic form for obtaining the current row that is linked to the currently selected grid row. This is expressed in long form, since in the short form (consolidated into one line), of all the type casting becomes quite mangled.
using System.Data;
CurrencyManager xCM =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataRowView xDRV = (DataRowView)xCM.Current;
DataRow xRow = xDRV.Row;
Using this form, xRow
will now contain a reference to the row in the DataTable
. Using xRow
you can now read the raw data from the bound DataTable
. If you are using typed DataSet
s, you will need to further type cast xRow
to the typed row.
Position
Wouldn't the Position
property be much simpler? Well yes, and no. You can use the Position
property as an index into the DataTable
rows, until a user sorts the grid by clicking on a column heading. The DataView
for the grid will then not match the DataTable
ordering and indexing will return the wrong records. Indexing into the DataView
is possible, but it still requires many type casts to achieve.
Shortcutting
Hopefully, in a future version of WinForms, Microsoft will take note and add a CurrentRow
property to the DataGrid
for easy access. Until then the logical alternative is to create a custom control and add this property ourselves. While creating custom controls is not difficult, creating a custom assembly and installing it into the toolbox for one method is a bit much. Instead, you can use the following short cut.
public class Global {
public Global() {
}
public static DataRow CurrentRow(DataGrid aGrid) {
CurrencyManager xCM =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataRowView xDRV = (DataRowView)xCM.Current;
return xDRV.Row;
}
}
This is defined as a static method, so now from your form code you can obtain the current row for a DataGrid
simply by using the following example:
DataRow xRow = Global.CurrentRow(MyDataGrid);
Nothing it this article is revolutionary, or advanced. But hopefully it will help you on your journey through WinForms...