【问题标题】:How to bind CheckBoxList to BitArray?如何将 CheckBoxList 绑定到 BitArray?
【发布时间】:2017-12-19 21:29:21
【问题描述】:

有带有项目的 CheckBoxList:

<asp:CheckBoxList ID="RadCheckBoxList1" runat="server" RepeatDirection="Horizontal"
    RepeatLayout="Flow">
    <Items>
        <asp:ListItem Text="" Value="1" />
        <asp:ListItem Text="" Value="2" />
        <asp:ListItem Text="" Value="3" />
    </Items>
</asp:CheckBoxList>

在 C# 代码中绑定时:

BitArray ba = new BitArray(3);
ba[0] = false;
ba[1] = true;
ba[2] = false;
cbl.DataSource = ba;
cbl.DataBind();

我预计: to see just marked checkboxes with no text

但结果是: Boolean values went to label texts

我不需要标签文本。只需要通过 BitArray 项中的布尔值设置复选框标记。 如果重要的话,大约有 600 个 CheckBoxList 控件,每个控件大约有 20 个复选框。所以制作单独的类会降低网页的性能。 BitArray 项目的属性名称是什么来绑定它 CheckBoxList 或者如何有效地绑定它?

编辑: 感谢fightc2通过设置

cb1.DataTextFormatString =  " ";

我摆脱了标签文本,但复选框仍未正确设置。而不是正确设置“checked”属性:

<input name="cbl3$1" id="cbl3_1" type="checkbox" value="">
<input name="cbl3$0" id="cbl3_0" type="checkbox" checked="checked" value="">

错误地设置了“值”属性:

<input name="cbl2$0" id="cbl2_0" type="checkbox" value="False">
<input name="cbl2$1" id="cbl2_1" type="checkbox" value="True">

【问题讨论】:

    标签: c# asp.net binding checkboxlist bitarray


    【解决方案1】:

    在调用 DataBind() 之前添加这行代码:

    cb1.DataTextFormatString =  " ";
    

    它们应该是 - 如果您循环遍历这些项目(比如单击按钮),您应该会看到值设置正确:

    protected void OnClick(object sender, EventArgs e)
    {
        foreach (ListItem item in cb1.Items)
        {
            var result = bool.Parse(item.Value);    
            System.Diagnostics.Debug.WriteLine(result);            
        }
    }
    

    【讨论】:

    • 好在标签消失了,但复选框未设置为来自 BitArray 的布尔值。
    • 我看到正确的值,但标记错误: 我把第二个 CheckBoxList 放在标记中的复选框是: ... 在网页上正确呈现: 属性“value”错误。需要设置属性“checked”。
    【解决方案2】:

    您只是绑定数据。如果您还想设置值,您将不得不循环这些值。您可以使用返回完整 RadioButtonList 的方法。这样您就不必单独循环每个列表。

    PlaceHolder1.Controls.Add(getCompleteRadioButtonList(ba));
    
    public RadioButtonList getCompleteRadioButtonList(BitArray ba)
    {
        //create a new radiobuttonlist
        RadioButtonList rbl = new RadioButtonList();
    
        //do the binding
        rbl.DataSource = ba;
        rbl.DataTextFormatString = " ";
        rbl.DataBind();
    
        //loop the values to set the items that were just bound
        for (int i = 0; i < ba.Count; i++)
        {
            rbl.Items[i].Selected = ba[i];
        }
    
        //return the list
        return rbl;
    }
    

    【讨论】:

    • 到目前为止,我使用循环来设置复选框,但我希望分配 DataSource 和 DataBind() 应该更快地完成相同的操作。这两种方式 1 looping 和 2 DataBinding 不能一起使用。
    猜你喜欢
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2010-10-12
    相关资源
    最近更新 更多