GridView loses data during postback

后端 未结 5 1196
我在风中等你
我在风中等你 2021-01-12 09:22

I have an aspx.Page containing a gridview. The gridview is bound in code behind to a datasource only when no postback takes place and has enableviewstate = true (The page to

5条回答
  •  时光说笑
    2021-01-12 10:06

    You are missing the concept here. This a very elementary question which google can answer for you.

    Anyway, the thing is 'DataSource' of all DataBound control will behave as read-only and it will read when it needs to bind the control. To keep data existing you need some other way. Eg ViewState or Session

    • ViewState is like a pocket embed to page. Bigger will make page load slower if it's bigger. The objects you store will be serialized to string based data. Bigger object cause a larger viewstate and greater bandwidth. Keep in mind that object has to he serializable.

    • Session is like a pocket for each user and it stays on server, means faster than viewstate. But big session will consume more MB in RAM

    edit noooo u still got it wrong. Enable ViewState doesn't help. let's take a look at structure.

    
       
     
     
      
     
    
    

    the input is an (actual)ViewState. When u set enable ViewState to WebControls it will store 'some serializable(mostly value type)' data. In your case, GridView.EnableViewState means it will store some property in it's own (logical)ViewState not page ViewState.

    In code behind this.ViewState["someName"] = ...; is page ViewState. Let's take a look in server side code.

    this.ViewState["someName"] = somDataTable; // this won't work
    this.ViewState["someID"] = "abc"; // this work fine
    

    Because DataTable doesn't has ISerializable which viewstate needs to convert any object to string base. U could implement your own serilization and assign to viewstate eg convert DataTable to byte[] and assign to view state.

    try Session instead

提交回复
热议问题