checkbox列出在codeehind asp.net中默认选中的项目

本文关键字:默认 项目 net asp codeehind checkbox | 更新日期: 2023-09-27 18:14:57

在我的页面中,我有一个CheckBoxList控件,上面有7个项目。我想将这7个项目设置为在我的Page_load代码ihind中检查的。

我的页面:

<asp:CheckBoxList ID="WeeklyCondition" runat="server">
    <asp:ListItem Value="1">Sat</asp:ListItem>
    <asp:ListItem Value="2">Sun</asp:ListItem>
    <asp:ListItem Value="3">Mon</asp:ListItem>
    <asp:ListItem Value="4">Tue</asp:ListItem>
    <asp:ListItem Value="5">Wed</asp:ListItem>
    <asp:ListItem Value="6">Thu</asp:ListItem>
    <asp:ListItem Value="7">Fri</asp:ListItem>
</asp:CheckBoxList>

checkbox列出在codeehind asp.net中默认选中的项目

您可以使用循环CheckBoxList的items集合中迭代并更改Selected属性。

foreach (ListItem item in WeeklyCondition.Items) 
    item.Selected = true;

如果你想检查一些有条件的,你可以使用这样的东西:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
        if(someCondition)
           CheckBoxList1.Items[i].Selected = true;
    }
}

从这里

如何将复选框列表项设置为默认选中

第一种方式:

<asp:CheckBoxList runat="server" ID="CheckBoxList1">
    <asp:ListItem Selected="True">Item1</asp:ListItem>
    <asp:ListItem Selected="True">Item2</asp:ListItem>
    <asp:ListItem Selected="True">Item3</asp:ListItem>
    <asp:ListItem Selected="True">Item4</asp:ListItem>
    <asp:ListItem Selected="True">Item5</asp:ListItem>
</asp:CheckBoxList>

第二种方式:

页面文件:

<asp:CheckBoxList runat="server" ID="CheckBoxList">
    <asp:ListItem>Item1</asp:ListItem>
    <asp:ListItem>Item2</asp:ListItem>
    <asp:ListItem>Item3</asp:ListItem>
    <asp:ListItem>Item4</asp:ListItem>
    <asp:ListItem>Item5</asp:ListItem>
</asp:CheckBoxList>

CodeBehind:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < CheckBoxList.Items.Count; i++)
    {
        CheckBoxList.Items[i].Selected = true;
    }
}
<asp:ListItem Selected="True">Item1</asp:ListItem>

如何将复选框列表项设置为默认选中