RichardB
RichardB

Reputation: 606

C# Checkbox.Checked Property Not Reflecting Check Changes

I have a form with containing a datalist which is bound to a datasource which contains a list of items and a true/false flag. If true, the myCheck checkbox is checked:

<form id="myForm" runat="server">
    <asp:Button ID="save" runat="server" Text="Save" OnClick="save_Click" />
    <br />
    <asp:DataList runat="server" id="myList" onitemdatabound="myList_ItemDataBound">
    <HeaderTemplate>
        <th>Item Name</th>
        <th id="thCheck" runat="server">Check?</th>
    </HeaderTemplate>
    <ItemTemplate>
        <td id="tdName" runat="server"><%# Eval("Name") %></td>
        <td runat="server"><asp:CheckBox id="myCheck" runat="server" Checked="false" /></td>
    </ItemTemplate>
</asp:DataList>

On clicking save, I want to see which items have been checked. I am using the following to iterate through the items in the datalist:

protected void save_Click(Object sender, EventArgs e)
{
    String Name;
    Boolean omit;

    foreach (DataListItem item in myList.Items)
    {
        CheckBox omitCheck = (CheckBox)item.FindControl("myCheck");

        if (omitCheck != null)
        {
            if (omitCheck.Checked == true) // This line is my problem!!
            {
                // do stuff
            }
            break;
        }
    }

FindControl appears to work ok and returns a checkbox, however the value is always false, even if I have checked some of the boxes. If I set the value of the checkboxes to True in the aspx page, omitCheck.Checked is always true. ViewState is not disabled.

I'm new to this so sure there is an obvious answer.

Upvotes: 1

Views: 4778

Answers (1)

Evert
Evert

Reputation: 8541

what does the myList_ItemDataBound function look like? I suspect it needs a !IsPostback to not override entered values on the postback

Upvotes: 5

Related Questions