如何以编程方式选中复选框?

时间:2014-11-14 11:38:38

标签: c# asp.net

我创建了自定义控件,其中包含复选框列表

      <asp:CheckBoxList ID="chklLineOfAuthority"   RepeatColumns="3" RepeatLayout="Table"
        RepeatDirection="Horizontal" AutoPostBack="false" CausesValidation="false" runat="server">
    </asp:CheckBoxList>

在其ascx.cs文件中有一个类似

的函数
    public void FillLineOfAuthorityForProduct(string loastring)
    {
        //let's us consider loastring contains 

        string loastring = "Casualty, Credit, Motor Club";
        DataSet ds = new DataSet();
        LineOfAuthorityBL bl = new LineOfAuthorityBL(SessionContext.SystemUser);
        bl.FetchAll(ds);
        chklLineOfAuthority.DataSource = ds.Tables[bl.SqlEntityX];
        chklLineOfAuthority.DataTextField = "LineOfAuthorityX";
        chklLineOfAuthority.DataBind();
        ds = null;
        bl = null;

        string[] arrGroup = loastring.Split(',');

            foreach (object obj in arrGroup)
            {

                for (int i = 0; i < chklLineOfAuthority.Items.Count; i++)
                {
                    if (chklLineOfAuthority.Items[i].Value == obj.ToString())
                    {
                        chklLineOfAuthority.Items[i].Selected = true;
                    }
                }

            }
        }

然后输出应该像

enter image description here

我的意思是伤亡,汽车俱乐部,信用卡复选框应该被检查。上面的代码无效。

2 个答案:

答案 0 :(得分:0)

使用foreach循环遍历CheckboxList,然后将每个ListItem值与obj.ToString()进行比较(这将替换您的for循环。下面:

foreach (ListItem itm in chklLineOfAuthority.Items)
{
    if (itm.Value == obj.ToString())
    {
        itm.Selected = true;
    }
}

答案 1 :(得分:0)

试试这个。

foreach (object obj in arrGroup)
{                
     chklLineOfAuthority.Items.FindByText(obj.ToString()).Selected = true;   
}