How do I access a hidden column value from a DataGrid?

H

Harry Keck

OK, I can now use DataGridTextBoxColumn objects to
determine what columns get displayed on my datagrid when I
bind to a datatable. At some point, though, I need to
access an ID field that was in the dataset, but that was
not displayed.

If I use datagrid.Item, I can not seem to access any
values that were not displayed. I can not merely use the
index of the row in the datagrid to get the corresponding
row out of the datatable, because the order of the rows
may change in the grid by the user clicking the column
header.

Does anyone have a good technique for hiding an ID column
from being displayed in the DataGrid, but then having
access to that hidden column at runtime? Thank you.
 
P

Paul

Check on the currency manager for the binding
The position should be correct, but I would have to
refresh my memory on that one.
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hello Harry,

If you want to access the ID column from outside the grid, it's simple. Paul
is absolutely right, CurrencyManager is your best friend here. The trick is:

a) To obtain a reference to a CurrencyManager instance the DataGrid is
co-operating with. To do that:

CurrencyManager cm = (CurrencyManager)grid.BindingContext[grid.DataSource,
grid.DataMember];

This step will work for probably any kind of data source bound to the grid
(including arrays of objects).

b) To obtain an index of a current row in the grid. This is like 1, 2, 3:

int rowIndex = grid.CurrentCell.RowNumber;

This should be more reliable than CurrentRowIndex as you always get current
row number for the active table (in case of a DataSet with many tables
having relations).

c) To obtain a reference to a DataRowView corresponding to the current row.

DataView view = (DataView)cm.List;
DataRowView rowView = view[rowIndex];

int ID = (int)rowView.Row["ID"];

The last step is valid only for DataTables, DataSets, DataViews and similar
types of data sources - but not for collections or arrays of objects.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top