views:

271

answers:

4

I define an array in in the class, not in any method, as a global variable, in the same scope of method:

TextBox[,] tx = new TextBox[100,100];
TableCell[,] tc = new TableCell[100, 100];
TableRow[] tr = new TableRow[100];

And I initialize them in Page_Init event:

protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //only for initiializing
            for (int i = 0; i < 100; i++)
            {
                tr[i] = new TableRow();
                for (int j = 0; j < 100; j++)
                {
                    tx[i, j] = new TextBox();
                    tc[i, j] = new TableCell();
                }
            }

        }

    }

ut when I click a button or any post back event, the variables turn null again! What's wrong in that?

=========================================================================

That was solved by using Session to store them in, but now something missing. How to save the values in the text boxes into this Session container? And when to do that?

+5  A: 

Every time you do any postback, even if it's just to process a button click, you're working with a brand new instance of your page class. This is ASP.Net 101.

To fix it, remove the if (!IsPostBack) check. Then set the all their visible properties to False and add them to the page right away. When you find out how many you need, set the Visible property to "true" for that many controls.

Always two there are; no more, no less. A request and a response.

Joel Coehoorn
A: 

Did you try adding them to the page's Controls collection or to the Control collection of a control on the page such as a hidden panel?

Christian Pena
I put them in a table on the page in another event when I know the number needed. Is that wrong?
Ahmad Farid
@Ahmad: It could work, but It's not exactly a good idea.
Joel Coehoorn
+2  A: 

The page instance that hosts the fields lives as the server and is discarded at the end of the request. Web servers tend to be largely stateless, after all - allowing clustering etc.

The next request will create a new page instance (perhaps on a different machine, perhaps in a new AppDomain if it has recycled).

To keep the values between requests, you need to put them into session, and fetch them back yourself - or send them to the client in the request (and bring them back again).

Marc Gravell
+2  A: 

This is because the page is stateless. You need to persist the data within the page itself i.e. the ViewState:

public TextBox[,] tx
{
   get { return ViewState["tx"] as TextBox[,]; }
   set { ViewState["tx"] = tx; }
}
James
yeah thats a good idea and it works so far, but now something is missing. When shall i transfer the values in the text boxes to the view state?
Ahmad Farid
If you put the controls on the page at the right time, ASP.Net will worry about that for you.
Joel Coehoorn
You could use some javascript to detect the onunload event?
James