Click here to Skip to main content
15,940,246 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
I have a WebForm that contain a GridView, a textbox and a button. When i press on the button the data of the text box is added to the GridView. This is my code:
C#
public partial class MyClass : System.Web.UI.Page
{
   Static DataTable dt = new DataTable();
   DataRow dr;
   protected void Page_Load(object sender, EventArgs e)
   {
      if(!IsPostBack)
      {
         dt.Columns.Add("ServiceName", typeof(string));
         GridView1.DataSource = dt;
      }

      GridView1.DataBind();
   }
   protected void btn_Click(object sender, ImageClickEventArgs e)
   {
      dr = dt.NewRow();
      dr["ServiceName"] = txtBox.Text;
      dt.Add(dr);
   }
}


The problem is that I've chosen to make the datatable to be a static not to recreate it in each postBack but as a result of saving the static variable in the memory the data is not cleared when refreshing the page (Create a new object from this page) and the data of the DataTable "dt" is bound to the gridview at the beginning .. what can I use instead of the static variable?
thanks in advance
Posted
Updated 1-Aug-13 1:06am
v3

Use Session. Store DataTable in Session and retrieve and modify whenever you want.
 
Share this answer
 
Comments
Hend Riad 1-Aug-13 7:17am    
is the session better than the static from the performance point of view ?
That will depend. If you have small amount of data, then using Session will not create any problem.

But if you have thousands of record, then using Session is not a good idea. You have think of other workarounds something like doing a custom pagination to get less data at a time for the Grid.
Just avoid use of static.
you can use for loop for it.
 
Share this answer
 
Comments
Hend Riad 1-Aug-13 7:18am    
for loop is not solving the problem as the object is initialized each time i request the page
Hi,

Initialize DataTable object again in ispostback condition will solve your problem.

C#
protected void Page_Load(object sender, EventArgs e)
   {
      if(!IsPostBack)
      {
         dt=new DataTable(); // this will make your object null every time you load page.
         dt.Columns.Add("ServiceName", typeof(string));
         GridView1.DataSource = dt;
      }

      GridView1.DataBind();
   }
 
Share this answer
 
Comments
Hend Riad 1-Aug-13 7:25am    
i'm trying it now
Hend Riad 1-Aug-13 7:32am    
It fires exception : " Object reference not set to an instance of an object. " --> Null reference exception because at the first time the object is set to a value but in each postback it's not created it's just declared

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900