Adding Datagrid to Viewstate....?

abraptirl

New Member
When adding a datagrid dynamically in code behind it doesn't seem to get added to viewstate, so when a postback happens, if the datagrid is not re-created from scratch it gets wiped off the page. I need to be able to dynamically build a datagrid where I show some columns and don't show others and have viewstate remembered. It looks like datagrids cannot be added as a control to viewstate. Does anyone have a workaround for this?<BR><BR>Please help...this problem is plaguing me.<BR><BR>Thanks!If your datagrid is using a dataset for its datasource, you can save the dataset (as an XML string) to viewstate, then when the postback is performed in page_load recreate the dataset and rebind it to the datagrid.<BR><BR>Two subs handle it.<BR><BR>Sub xmlSaveIt()<BR>Dim strDSet as String<BR>strDSet = objDataSet.GetXml() <BR>ViewState("strData")=strDSet <BR>End Sub<BR><BR>Sub xmlGetIt()<BR>Dim strDSet as String<BR>strDSet = ViewState("strData")<BR>Dim strReader As New System.IO.StringReader(strDSet) <BR>objDataSet.Readxml(strReader) <BR>End Sub<BR><BR>If your dataset object (objDataSet) is page level scope, then you can call the xmlGetIt sub during page_load then follow this call with <BR><BR>DataGrid.DataSource = objDataSet<BR>DataGrid.DataBind()<BR><BR>This way your datagrid is persisted between post events.Why not add your datasource to viewstate and just rebind?? If you add or remove columns or anything you will have to rebind anyway.I have a templated column of checkboxes in my datagrid that I need to be able to keep track of. I am using these checkboxes to be able the edit or delete multiple records at the same time (like hotmail e-mail), so adding the datasource to viewstate won't achieve this goal.<BR><BR>Thanks.<BR>AOk, well how would adding the entire control to viewstate accomplish this goal? Just have them check the boxes then when they click edit or delete run through each item and see if it is checked or not.
 
Back
Top