DataGridView becomes null for some reason

久未见 提交于 2019-12-13 05:47:49

问题


I have a NET 2.0 framework ASP.NET application ..

The page I'm having trouble with has a button (B1), and the below that a DataGridView (DGV), and then below that a second button (B2) ..

Initially only B1 is visible. When user clicks B1, I do some DB queries, fetch some data, put it in a DataTable, and then set the DataSource of that DGV to this DataTable .. B1 also makes DGV and B2 visible, both of which were invisible before .. Now user fills in some data in the now-visible DGV and clicks B2 ..

Problem is that in B2's code, if I try to see the DataSource of that DGV, its null !? .. I need to access the updated values in that DGV .. How do I do that ?

I've tried a few hacks, but nothing seems to work .. I've sort of got it working through FindControl, but I don't want to use that because I need the original DataTable for other reasons (not mentioned here because they're quite complex) ..

Code behind B1, setting DataTable DataSource:

epsDGV.DataSource = epsDataDT; // epsDataDT is the DataTable:

Code behind B2, fetching DataTable:

DataTable epsDataDT2 = (DataTable)epsDGV.DataSource; //returns null


回答1:


DataSource is not available during a postback. It is used during the current page lifecycle to fill the grid with the relevant data for each row, and is then discarded.

If it didn't do this, then it would need to send it back to the client inside the viewstate. Given that you could have handed it a list containing thousands of records (only some of which it might be showing, depending on paging settings), it would cause huge bloat to the viewstate - all of which needs to be sent to the client, then back up to the server when you clicked on B2.

Instead, the grid control will keep track of the data populated into its columns. This will include the changes made during inline editing.

Most examples online I've found suggest using FindControl to get the new value back, and using ViewState to store (and retrieve) the datasource - if you really do need to save it. However, I would highly recommend against doing that unless you can guarantee that the datasource is very small - otherwise you risk choking the clients bandwidth (particularly if they are on a slow connection)

If you need to store it in Viewstate, just create a property like below (NB: your datasource object needs to be serializable, or it won't be able to get stored in the ViewState):

public List<Items> Items
{
    get 
    {
        if (ViewState["Items"] != null)
            return (List<Items>)ViewState["Items"];
        else
            return null;
    }
    set { ViewState["Items"] = value; }
}

then set it during your Data Load methods. On postback, you can call the property to pull it back out of the Viewstate.



来源:https://stackoverflow.com/questions/21067997/datagridview-becomes-null-for-some-reason

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