简体   繁体   中英

C# asp.net Checkbox in checkboxlist returns unchecked always

I've been breaking my head on this one for a day now. But I just don't see it.

I have a checkboxlist named cblRounds which is

<asp:CheckBoxList ID="cblRondes" runat="server">
</asp:CheckBoxList>

Also to note, EnableViewstate is set to true.

In my code behind, in the page_Load i fill de list like this:

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        dpPrintRounds.FieldValue = DateTime.Now.AddDays(1);

    }
    FillCheckBoxList(); 
}

private void FillCheckBoxList()
{
    tourCollectie = new LogisticsTourCollection();
    RelationCollection rc = new RelationCollection(LogisticsItemEntity.Relations.LogisticsItemSpecsEntityUsingSeqSpecs);
    rc.Add(LogisticsItemSpecsEntity.Relations.LocationEntityUsingSeqLocationDelivery);
    rc.Add(LocationEntity.Relations.LocationLogisticsTourEntityUsingSeqLocation);
    rc.Add(LocationLogisticsTourEntity.Relations.LogisticsTourEntityUsingSeqLogisticsTour);
    PredicateExpression pe = new PredicateExpression(LogisticsItemSpecsFields.RequiredDeliveryDate == dpPrintRounds.FieldValue);
    pe.Add(LogisticsItemFields.DeliveryNumber != DBNull.Value);
    tourCollectie.GetMulti(pe, rc);

    cblRondes.Items.Clear();
    foreach (LogisticsTourEntity tour in tourCollectie)
    {
        cblRondes.Items.Add(new ListItem(tour.Name, tour.SeqLogisticsTour.ToString()));
    }        
}

Then I click a button where I check the checkstate of the checkboxes

protected void btnPrintHeaders_Click(object sender, EventArgs e)
{
    PrintRounds();
}

private void PrintRounds()
{
    if (dpPrintRounds.Date_Selected.HasValue)
    {            
        Dictionary<string, string> rondes = new Dictionary<string, string>();
        foreach (ListItem item in cblRounds.Items)
        {
            if (item.Selected)
            {
                rondes.Add(item.Value, GetDeliveryNumberFromRonde(item.Value));
            }
        }            


    }
}

Everything works correct except that the if (item.Selected) always returns false.

Also I have

<td>
            <rm:DatePicker ID="dpPrintRounds" runat="server" />
        </td>
        <td>
            <asp:Button ID="btnSearch" runat="server" Visible="true" 
                onclick="btnSearch_Click" />
            <%--<asp:Literal ID="litLogisticsRoundName" runat="server" />:--%>
        </td>

The Datepicker returns a date I use to filter my collection. So when I press the searchbutton, I get "new" checkboxes in my checkboxlist. This is why I DON'T have the Fillcheckboxlist inside the if(!IsPostBack) else I get no checkboxes on a new search.

I've been searching for an answer on this and tried several things but none seem to work. Any ideas are appreciated.

Page_Load event code must be wrapped in IsPostBack block.

if(!IsPostBack)
{
  foreach (LogisticsTourEntity tour in tourCollection)
    {
        cblRounds.Items.Add(new ListItem(tour.Name, tour.SeqLogisticsTour.ToString()));
    }
}

Demo:

Markup

<form id="form1" runat="server">
    <asp:CheckBoxList 
            ID="cblRounds" 
            runat="server">
    </asp:CheckBoxList>
    <asp:Button 
            ID="Button1" 
            runat="server" 
            Text="Button" onclick="Button1_Click" />

</form>

Code-behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
    for (int i = 1; i <= 10; i++)
    {
        cblRounds.Items.Add(new ListItem("Text" + i ,i.ToString()));
    }
}
}
protected void Button1_Click(object sender, EventArgs e)
{
PrintRounds();
}
private void PrintRounds()
{
    Dictionary<string, string> rondes = new Dictionary<string, string>();
    foreach (ListItem item in cblRounds.Items)
    {
        if (item.Selected)
        {
            rondes.Add(item.Text , item.Value);
            Response.Write("<br/> " + item.Text + " " + item.Value);
        }
    }

}

Your method call FillCheckBoxList() populates the listbox on page load, whether it is a postback or not.

That means you are overriding the values posted back to the server, as your fill code always executes this:

cblRondes.Items.Clear();
foreach (LogisticsTourEntity tour in tourCollectie)
{
    cblRondes.Items.Add(new ListItem(tour.Name, tour.SeqLogisticsTour.ToString()));
}

You want to only populate the CheckBoxList's items if it it not a postback (ie only when the page first loads).

When it is a postback the Items collection of the CheckBoxList has already been populated by the postback itself from the contents of the webpage . You do not have to populate the control on postback.

You just want to change your page_load to:

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        dpPrintRounds.FieldValue = DateTime.Now.AddDays(1);
        FillCheckBoxList(); 
    }
}

In answer to the original question, a look here may help someone:-

http://aspdotnetcodebook.blogspot.co.uk/2008/08/how-to-add-checkboxlist-dynamically.html

I have successfully dynamically created a checkboxlist, populated it with values from a db and then after changes updated the database.

Have you ensured it is not due to casting to ListItem? It shouldnt be needed but worth a try...

for (int i = 0; i < cblRounds.Items.Count; i++)
{
   if (cblRounds.Items[i].Selected)
     //do your stuff
}

Also if you set a breakpoint to the place where you are dereferencing the Selected value what is it's state? Could this be an issue with at what point in the page life cycle you are binding data/user event being captured vs. where you are trying to get the selected value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM