views:

1072

answers:

2

I have an ASP.NET 3.5 GridView on a WebForm. The GridView gets data from an ObjectDataSource which is set via the DataSourceID property in the code in front. The ObjectDataSource returns a List of custom data class objects (just a class with public properties) to populate the GridView.

What I want to do is use the a List comsumed by the GridView in another code-behind method. At a high level: 1. GridView is loaded with List data from ObjectDataSource. 2. In the GridView.OnDataBound method I call GridView.DataSource to get the List object. 3. I enumerate the List and use the same data to do some other operation.

The theory being one less duplicated method call and one less call to the back-end database.

I've tried calling DataSource from the GridView' DataBound method and calling GridView.Rows[x].DataItem. In each case I only get a Null reference exception ("Object reference not set to an instance of an object").

Is there any way to achieve what I'm after?

A: 

If I understand you correctly, you want the OnRowDataBound event. This way, you can use data from the row that was just databound:

protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    CustomDataClass data = e.Row.DataItem as CustomDataClass;
    if (data != null) 
    {
        // access data here...
    }
}
John Rasch
A: