0

i had a DataList view which i add a check box in the Item Template

i want each item i select to increase some counter for examble once it's checked .. i used the following code to handle that ,but the event function is never accessed ?!

    protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
    {        
    int selected = 0;
    foreach (DataListItem i in DataList1.Items)
    {
        CheckBox chk = (CheckBox)i.FindControl("selectItemCheckBox");
        if (chk.Checked)
        {

            selected++;
        }
        selectedItemCount.Text = Convert.ToString(selected);
        }`
     }
3
  • 2
    Did you make AutoPostBack="True"? msdn.microsoft.com/en-us/library/… Commented Dec 7, 2012 at 15:07
  • 1
    Can u please post some .aspx code. Commented Dec 7, 2012 at 15:13
  • Have you assigned the event handler to the control? <asp:CheckBox id="selectItemCheckBox" runat="server" OnCheckedChanged="selectItemCheckBox_CheckedChanged" /> Commented Dec 7, 2012 at 15:21

1 Answer 1

1

Currently you're looping over every checkbox for every checked checkbox which is inefficient and depending on your other code, may be causing trouble.

You're better off incrementing for each checkbox individually.

...DataList...
<ItemTemplate>
    <asp:CheckBox id="selectItemCheckBox" runat="server"
        AutoPostBack="True"
        OnCheckedChanged="selectItemCheckBox_CheckedChanged" />
</ItemTemplate>
...DataList...

After a box is checked, update the total for just that checkbox using sender

protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
{
    // Parse the total selected items from the TextBox.
    // You may consider using a Label instead, or something non-editable like a hidden field
    int totalChecked;
    if (int.TryParse(selectedItemCount.Text, out totalChecked) = false)
        totalChecked = 0;

    // Get a reference to the CheckBox
    CheckBox selectItemCheckBox = (CheckBox)sender;

    // Increment the total
    if (selectItemCheckBox.Checked == true)
        totalChecked++;

    // Put back in the TextBox
    selectedItemCount.Text = totalChecked.ToString();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.