Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Some problem with Page_Load

Status
Not open for further replies.

Sahikon

Programmer
Nov 12, 2003
4
0
0
RU
I have VS.NET Beta 2

my code:
Code:
...
private static int i;
private void Page_Load(object sender, System.EventArgs e)
{
     i++;
     Label7.Text = i.ToString();
     ....
}
...

When the page was loaded, the text of the label was "3".
I don't understand this. Why "3"?

 
Not entirely sure. Somewhere in your code you may be incrementing i twice more.

Or more likely it's because you've declared it as a static member. I am still a little fuzzy on how static members work exactly. However, I do know that they don't belong to the class that calls them. It seems as though i isn't reset when the page class is loaded or unloaded (sent to browser then back on post-back) I want to look into this further myself but I did some testing and the variable i keeps it's value from the last time it was incremented.

If you don't want this to happen don't use the static modifier or when you declare i make sure to initialize it as well.
private static int i = 0;

That'l do donkey, that'l do
[bravo] Mark
If you are unsure of forum etiquette check here faq796-2540
 
I was correct in my explanation. A static variable is part of the class in that it is access by ClassName.variablename, however thats the extent of it. If you have 3 classes of the same type initialized and you change the static variable in one of them it will be changed in all 3 classes. It's kind of a "global" variable of types.

Hope this has helped

That'l do donkey, that'l do
[bravo] Mark
If you are unsure of forum etiquette check here faq796-2540
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top