skip to Main Content
List< ABC > lstABC = new List< Abc >();//MyList
ViewState["Test"] = lstAbc;    //passed to viewstate 
Datatable dt = (Datatable)ViewState["Test"]; // but datatable Not accepting viewstate with binded list values. 

2

Answers


    1. Create a datatable

    DataTable DT = new DataTable();

    2)add columns to that Datatable

    DT.Columns.Add("columnname1", typeof(DateTime));
    DT.Columns.Add("columnname2", typeof(String));
    
    1. add the rows to that Datatable

      DT.Rows.Add(DateTime.Now, "someString"); //repeat for more rows

    2. store the dataTable in the viewstate
      Viewstate["VSDT"] = DT;

    5)Where you want to call that DataTable
    Create a new DT

    DataTable NewDT= new DataTable();
    NewDT= (DataTable)ViewState["VSDT"];
    
    Login or Signup to reply.
  1. I would suggest to first make sure the class of the object you are passing in the ViewState is serializable

    [Serializable]
    public class ABC
    

    Then, as toly P said, you want to create your datatable, instantiate the columns and add rows. For this you could either use your object type (example 1), or you could use every parameter inside of it.. let’s say an id (int) and a name (string) (example 2)

    Example 1:

    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("ColumnName1", typeof(ABC)));
    foreach(var item in ViewState["Test"] as List<ABC>)
    {
        dt.Rows.Add(item)
    }
    

    Example 2:

    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("ColumnName1", typeof(int)));
    dt.Columns.Add(new DataColumn("ColumnName2", typeof(string)));
    foreach(var item in ViewState["Test"] as List<ABC>)
    {
        dt.Rows.Add(item.id, item.name)
    }
    

    You don’t want to store the datatable in the ViewState because it isn’t serializable. Instead, you store the list and instantiate the DataTable on each load.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search