KotMorderca
KotMorderca

Reputation: 31

Determine if CheckBox is checked in ASP.NET

I have problem with determine if checkbox is checked on my webpage build in ASP.NET. When I render webpage in Page_Load method I check some of checkbox using code like:

checkbox1.Checked = true;

On page I have button to process data in form, on click in this button i check if checkbox was checked:

if(checkbox1.Checked == true)
{
    //do something
} else {
    //do something else
}

But i found that value which I get from Checked property is always same as I set in first step. That property never returns value of current state of CheckBox. And here is my question: Why?

I menaged to bypass that problem by setting checked in different way:

checkbox1.Attributes.Add("checked","true");

I don't like when something works but I don't know why so please give me advise what I'm misunderstanding.

Upvotes: 1

Views: 19059

Answers (2)

mason
mason

Reputation: 32699

You do know that Page_Load runs after every postback, before it executes your control event handlers such as Button_Click? You're probably resetting the values every time the page loads. You should write your initialization code inside an if statement to make sure you don't overwrite the value that was posted back.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        checkbox1.Checked = true;
    }
}

Also,

if(checkbox1.Checked == true)
{
    //do something
} else {
    //do something else
}

Since the checkbox1.Checked value is a Boolean already, there's no need to compare it to true. When you read the code verbally it's like saying "If the checkbox is checked, and the previous statement I just said is true". You can shorten it, so that it reads more like "If the checkbox is checked".

if(checkbox1.Checked)
{
    //do something
} else {
    //do something else
}

Upvotes: 2

walther
walther

Reputation: 13600

In your Load event you're probably missing part with IsPostBack, so it executes every time and end up rewriting your values.

protected void Page_Load(object sender, EventArgs e)
{
      if (!IsPostBack)
      {
           // do initial initialization here
      }

      // this happens even during a postback
}

Upvotes: 2

Related Questions