How do I get Gridview underlying datasource?
i have gridview in my asp.net web application under framework 3.5. I am binding the gridview with List. Inside the grid there is update and delete functionalities which are running fine. But my save functionality, for which i decided to extract the list back from the datasource and then through loop i will insert the new list to database. But when i tried to get it conventional way it return开发者_如何学运维ed me null.
I tried the following ways to retrieve the List back.
1. List<MyClass> list = (List<MyClass>gv.DataSource);
2. List<MyClass> list = gv.DataSource as List<MyClass>;
3. IDataSource idt = (IDataSource)gv.Datasource;
List<MyClass> list = (List<MyClass>)idt;
But no luck, each time i got null.
You cannot retreive the datasource once is is bound and the page is served. You have a few methods available to you to retain the datasource though:
- Store the data before binding in the
Session
- Store the data before binding in the
ViewState
- Fetch the data from the DB or whatever data store you retrieved it from originally.
- Keep an ongoing cache of changes stored somewhere else (eg
Session
,ViewState
, etc)
I prefer to stay away from drag and drop useage of datasources and binding data though.
So in your case store the list somewhere accessible and manipulate it as you go along and rebind it each time. Then when you want to do that 'save' you can just deal with the underlying data object (List
) that you have stored and is being used to define the GUI. The GridView
is not a datastore, just a control to present the data based on a data store.
You can go through all the items of the gridview and add all the items back to a new List you create.
Something like this is what I use:
List<Categories> myList = new List<Categories>();
foreach (GridViewRow row in grdCategory.Rows)
{
Categories newCat = new Categories();
Label catID = row.FindControl("lblCatID") as Label;
newCat.catID = Convert.ToInt32(catID.Text);
...
...
myList.Add(newCat);
}
It has been some time since this question was posted, but I hope this helps someone.
Once the list is bound and the web page is displayed, the DataSource is gone. You need to recreate the datasource and access the particular object using a primary key.
精彩评论