2013-08-28 47 views
0

我要存儲在ViewState中c# - 如何在ViewState中存儲ArrayList?

ArrayList的價值,但我得到了一個錯誤:

"Type 'System.Data.DataRow' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable" 

代碼:

private void bindGridView() 
    { 
     DbConnection.Open(); 
     OleDbCommand DbCommand = new OleDbCommand("select emp_id,emp_name,father_name,gender,designation,department,location from emp_master", DbConnection); 
     OleDbDataAdapter Dbreader1 = new OleDbDataAdapter(DbCommand); 
     DataSet dsemer = new DataSet(); 

     Dbreader1.Fill(dsemer); 
     ArrayList arrList = new ArrayList(); 
     foreach (DataRow dtRow in dsemer.Tables[0].Rows) 
     { 
      arrList.Add(dtRow); 
     } 
     //Here getting an error 
     ViewState["ds"] = arrList; 
     EmpMasterGrid.DataSource = dsemer; 
     EmpMasterGrid.DataBind(); 

     DbConnection.Close(); 
    } 

爲什麼我需要存儲的ArrayList中的ViewState?

通過使用ViewState的,我會選擇出口GridView的列Excel中使用下面的代碼

private void GetCheckBoxStates() 
    { 
     CheckBox chkCol0 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol0"); 
     CheckBox chkCol1 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol1"); 
     CheckBox chkCol2 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol2"); 
     CheckBox chkCol3 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol3"); 
     CheckBox chkCol4 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol4"); 
     CheckBox chkCol5 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol5"); 
     CheckBox chkCol6 = (CheckBox)EmpMasterGrid.HeaderRow.Cells[0] 
           .FindControl("chkCol6"); 
     ArrayList arr; 

     if (ViewState["ds"] == null) 
     { 
      arr = new ArrayList(); 
     } 
     else 
     { 
      arr = (ArrayList)ViewState["ds"]; 
     } 
     arr.Add(chkCol0.Checked); 
     arr.Add(chkCol1.Checked); 
     arr.Add(chkCol2.Checked); 
     arr.Add(chkCol3.Checked); 
     arr.Add(chkCol4.Checked); 
     arr.Add(chkCol5.Checked); 
     arr.Add(chkCol6.Checked); 
     ViewState["ds"] = arr; 
    } 

任何想法?提前致謝。 已編輯!

回答

0

由於錯誤導致System.Data.DataRow不可序列化,因此您無法將其存儲在ViewState中。

我會建議你做一個包含所有你需要的值標記爲Serializable自定義類,並保存這些對象的ArrayListViewState。您將使用DataRow中的數據在您的foreach循環中填充這些對象。

例子:

數據對象

[Serializable] 
public class Employee 
{ 
    public int emp_id, 
    public string emp_name, 
    //other properties 
} 

在你bindGridView方法

//other code 
ArrayList arrList = new ArrayList(); 
foreach (DataRow dtRow in dsemer.Tables[0].Rows) 
{ 
    arrList.Add(new Employee 
    { 
     emp_id = dtRow[0], 
     emp_name = dtRow[1], 
     //other properties 
    }; 
} 
ViewState["ds"] = arrList; 
+0

感謝您的努力,BU還是我得到一個錯誤 – user2500094

+0

如何添加數據集值,而不是下面這行中的ArrayList arr.Add(chkCol0.Checked); – user2500094