How do I get Gridview underlying datasource?

梦想的初衷 提交于 2020-01-03 20:02:36

问题


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 returned 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.


回答1:


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:

  1. Store the data before binding in the Session
  2. Store the data before binding in the ViewState
  3. Fetch the data from the DB or whatever data store you retrieved it from originally.
  4. 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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5171816/how-do-i-get-gridview-underlying-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!