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.
If I declare a class-level boolean variable showLabels like:
private bool showLabels = false;
and then have the following code:
if(showLabels == false)
{
showLabels = true;
imgShowLabels.ImageUrl = "label-on.png";
}
else
{
showLabels = false;
imgShowLabels.ImageUrl = "label-off.png";
}
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.
So what I did was change it from:
private bool showLabels = false;
to
private static bool showLabels = false;
and it is working this way.
Is this the correct way to handle this type of scenario?
In the class level, I put the property:
public bool ShowLabels
{
get { return (bool)ViewState["ShowLabels"]; }
set { ViewState["ShowLabels"] = value; }
}
In the if(!Page.IsPostBack), I am setting ShowLabels to false;
Then in my if statement, I am doing:
if(ShowLabels == false)
{
ShowLabels = true;
imgShowLabels.ImageUrl = "label-on.png";
}
else
{
ShowLabels = false;
imgShowLabels.ImageUrl = "label-off.png";
}
But ShowLabels is always false, I thought by setting the ViewState through the property ShowLabels, it would retain its value.