Search code examples
asp.net.net-4.0webforms

Why are my ASP.NET checkboxes always false?


I'm working on a ASP.NET web forms application. I have a four-column listview, bound to a datasource on pageload(), populated with contact names. One of the columns contains a checkbox. Users select a checkbox to indicate the corresponding contact should be processed in the next step.

The form also contains a button. When this button is clicked, the following code runs to process the selected contacts.

foreach (var x in lvPeople.Items)
{
    chkSelected = (CheckBox)x.FindControl("IsLetterRecipient");

    if (chkSelected.Checked)
    {
       // the person was selected by the user, do stuff here...
    }
}

When I set a breakpoint on the line containing the IF statement, the breakpoint gets hit seven times (once for each row in the listview == seven checkboxes). However, the code inside the IF block never runs because .Checked is always False, regardless of the whether or not the checkbox is actually checked.

AutoPostBack, on the checkbox, is set to False. EnableViewState on the checkbox and listview is set to True.

What am I doing wrong? How do I get the .Checked status of the checkboxes?


Solution

  • Probably, when you bind the data on Page_Load you forgot to do:

    if(!IsPostBack)
    {
        //bind the data to the list
    }