页面首次加载时,如何检查复选框列表中的所有复选框? [英] How to check all checkboxes in a checkboxlist when page first loads?

查看:80
本文介绍了页面首次加载时,如何检查复选框列表中的所有复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来很简单,但我无法弄清楚.我已经尝试过以下代码:

Seems simple enough, but I can't figure it out. I've tried this code:

    protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        foreach (ListItem item in CheckBoxListDivision.Items)
            item.Selected = true;
    }
}

和此标记:

           <asp:CheckBoxList ID="CheckBoxListDivision" runat="server" DataSourceID="SqlDataSourceDivisions" DataTextField="Divisions" DataValueField="Divisions" RepeatColumns="4">
        </asp:CheckBoxList>
        <asp:SqlDataSource ID="SqlDataSourceDivisions" runat="server" ConnectionString="<%$ ConnectionStrings:WebPortal_Call4HealthReports_ConnectionString %>" SelectCommand="usp_HR_DivisionsSelectAll" SelectCommandType="StoredProcedure"></asp:SqlDataSource>

感谢您的时间和精力.

推荐答案

之所以没有选择项目,是因为在绑定CheckBoxList项目之前调用了Page_Load事件.因此,为了在页面加载时选择所有项目,您有两个选择:

The reason it's not selecting the items is that Page_Load event is called before binding the CheckBoxList items. So in order to select all the items when page loads you have two options:

第一个选项:在CheckBoxList的 OnDataBound 事件中放入您正在使用的相同代码.

First option: Put the same code you're using in the OnDataBound event of the CheckBoxList.

修改CheckBoxList标记为:

Modify the CheckBoxList markup to this:

   <asp:CheckBoxList OnDataBound="CheckBoxListDivision_DataBound"
 ID="CheckBoxListDivision"  runat="server" DataSourceID="SqlDataSourceDivisions" DataTextField="Name" DataValueField="ID" 
            RepeatColumns="4" >
    </asp:CheckBoxList>

并在代码后面添加它:

protected void CheckBoxListDivision_DataBound(object sender, EventArgs e)
   {
       foreach (ListItem item in CheckBoxListDivision.Items)
       {
           item.Selected = true;
       }
   }

第二个选项:从标记中删除SqlDataSource,并在Page_Load事件中以编程方式绑定CheckBoxList ,然后在绑定CheckBoxList之后,执行循环即可选择项目.

Second option: Remove the SqlDataSource from your markup and bind the CheckBoxList programatically in Page_Load event, then after binding the CheckBoxList, do the loop and you'll be able to select the items.

希望这会有所帮助.

这篇关于页面首次加载时,如何检查复选框列表中的所有复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆