Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple question about how static variables work in ASP.NET?
    primarykey
    data
    text
    <p>I have a map which displays some info. By default, labels on the map are turned off. There is an image button which has a turned-off image associated with it when you the labels are off and a turned-on image associated with it when you turn the labels on. I have the code working, but I wanted a better reason as to why it works this way. Here is a snippet of code.</p> <p>If I declare a class-level boolean variable showLabels like:</p> <pre><code>private bool showLabels = false; </code></pre> <p>and then have the following code:</p> <pre><code>if(showLabels == false) { showLabels = true; imgShowLabels.ImageUrl = "label-on.png"; } else { showLabels = false; imgShowLabels.ImageUrl = "label-off.png"; } </code></pre> <p>When I run it, the map comes up with the labels not shown by default. When I click on the Show Labels button, the variable showLabels becomes true and the image is changed to label-on.png, but when I click it again, the showLabels variable is reset to false, so nothing happens.</p> <p>So what I did was change it from:</p> <pre><code>private bool showLabels = false; </code></pre> <p>to</p> <pre><code>private static bool showLabels = false; </code></pre> <p>and it is working this way.</p> <p>Is this the correct way to handle this type of scenario?</p> <p>In the class level, I put the property:</p> <pre><code>public bool ShowLabels { get { return (bool)ViewState["ShowLabels"]; } set { ViewState["ShowLabels"] = value; } } </code></pre> <p>In the if(!Page.IsPostBack), I am setting ShowLabels to false;</p> <p>Then in my if statement, I am doing:</p> <pre><code>if(ShowLabels == false) { ShowLabels = true; imgShowLabels.ImageUrl = "label-on.png"; } else { ShowLabels = false; imgShowLabels.ImageUrl = "label-off.png"; } </code></pre> <p>But ShowLabels is always false, I thought by setting the ViewState through the property ShowLabels, it would retain its value.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload