Hi,
I am experimenting to make a datatable in C# code in a page. This table should be a disconected table with Only valid for the present session.
I try the following code:
publicpartialclassDefault2 : System.Web.UI.Page
{
DataTable DT =newDataTable("TEST");
protectedvoid Page_Load(object sender,EventArgs e)
{
if (!IsPostBack)
{
DataColumn Col1 =newDataColumn("Col1");
Col1.DataType =typeof(Int32);
Col1.AllowDBNull =false;
DT.Columns.Add(Col1);
DataColumn Col2 =newDataColumn("Col2");
Col2.DataType =typeof(string);
Col2.AllowDBNull =true;
DT.Columns.Add(Col2);
DataColumn Col3 =newDataColumn("Col3");
Col3.DataType =typeof(DateTime);
Col3.AllowDBNull =true;
DT.Columns.Add(Col3);
GridView1.DataSource = DT;
}
}
protectedvoid Button1_Click(object sender,EventArgs e)
{
for (int i = 1; i < 20; i++)
{
DataRow MyRow = DT.NewRow();
MyRow["Col1"] = i;
DT.Rows.Add(MyRow);
}
}
}
For one reason or the other. if I click the button I get the message that Col1 dus not make part of the table TEST. It turns out that there are no columns added to the table. altroug the code in the page load part has been run. I suppose I have to do something with the session state to make my DataTable persistent, but I have no idea what. Can somebody help me out?
Thanks!
Rob
You've got the right idea. If you want to save your DataTable within the Session, just change your 'DT' reference to something like this:
private DataTable DT{get{if (this.Session["DT"] ==null){this.Session["DT"] =new DataTable("Test");}return this.Session["DT"]as DataTable;}set {this.Session["DT"] =value; }}|||
Great! It works. Only one more question. The Datagrid is not updating the records. Do you maybe have also a solution for that?
many thanks
rob
|||What do you mean by not updating the records?
|||I have put a gridview on the form, and thougt that with the statementGridView1.DataSource = DT;
I would automaticly see the rows from the data table in de gridview.
But ASP always works the unexpected ways. . .
|||Add this to the bottom of your Button1_Click event:
GridView1.DataSource =this.DT;GridView1.DataBind();|||
I thank you very mutch. It works great.
regards Rob
No comments:
Post a Comment