I need to retrieve the data contained inside a WebDataGrid. What is the best way to do it?
At first I thought I could do something like this below (ADO.NET DataTable style) :
I know I can get the value using the column index rec.Items[0].Value . Is there a way I can use the column Key name?
Thanks
Daniel
Hi Daniel,
I recommend you to use the DataItem property, for example if you bind to a DataSet/DataTable/SqlDataSource you just need to cast the data item as a DataRowView:
foreach (Infragistics.Web.UI.GridControls.GridRecord rec in WebDataGrid1.Rows) { object value = ((DataRowView)rec.DataItem)["FirstName"]; }
Hope that helps!
That would be great!... but my rec.DataItem is always null... :(
I am loading the Grid from a button event and I load it using a DataTable in memory.
devdti said:That would be great!... but my rec.DataItem is always null
I'm not sure what's your exact setup, is DataItem happening to be null on postback? When restoring data from viewstate (on postback) data items may be null.
The second option I can suggest is this:
int columnIndex = WebDataGrid1.Columns["LastName"].Index;foreach (Infragistics.Web.UI.GridControls.GridRecord rec in WebDataGrid1.Rows){ object value = rec.Items.GetValue(columnIndex); }
After verification, the DataItem contains the data just after I set the Grid.DataSource property.
But after a postback the DataItem is null. I have set the Grid.ViewState = true and Grid.DataViewState = true. I thought that it would keep those values in the ViewState.
That would be REALLY annoying to have to retrieve the index of each columns to retrieve the data. I have about 20 columns I need to retrieve values.
Isn't there any other way to do that? :(
WebDataGrid does not serialize the whole DataItem in the view state, only the grid record values. That's why DataItem is null on postback. If you still want to use it you may disable data view state and set grid DataSource on postback.
devdti said:That would be REALLY annoying to have to retrieve the index of each columns to retrieve the data.
I see, surely this is annoying. I would suggest you to add a simple method which returns record value by column name:
private object GetRecordValue(GridRecord rec, string columnName){ int columnIndex = WebDataGrid1.Columns[columnName].Index; return rec.Items.GetValue(columnIndex); }
foreach (Infragistics.Web.UI.GridControls.GridRecord rec in WebDataGrid1.Rows){ object value = GetRecordValue(rec, "LastName"); }
Hope that's ok, even better if you are working with .Net framework 3.5 you can add this as extension method to GridRecord.