Ahmed Moheb
Ahmed Moheb

Reputation: 762

CheckBox handling oncheck changed in ASP.net

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);
        }`
     }

Upvotes: 0

Views: 2656

Answers (1)

Kirk
Kirk

Reputation: 16245

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();
}

Upvotes: 1

Related Questions