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

1 回答 1

1

目前,您正在为每个选中的复选框循环遍历每个复选框,这效率低下,并且取决于您的其他代码,可能会造成麻烦。

你最好单独增加每个复选框。

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

选中一个框后,使用发件人更新该复选框的总数

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();
}
于 2012-12-07T16:45:42.147 回答