c# - CheckboxList 忽略 DataValueField 和 DataTextField

标签 c# checkboxlist

我发现了这个错误。它是如此显而易见:我没有将数据绑定(bind)到正确的复选框列表!我应该将数据绑定(bind)到filterONTYPElist,但我正在将数据绑定(bind)到filterONDATASETlist...复制粘贴错误,抱歉...

我有一个呈现如下的复选框列表:

enter image description here

这是处理数据绑定(bind)的代码:

FilterOnTypeCheckboxList.DataSource = listCheckboxItems;
FilterOnDatasetCheckboxList.DataValueField = "Value";
FilterOnDatasetCheckboxList.DataTextField = "Text";
FilterOnTypeCheckboxList.DataBind();

我的数据源是 list<CheckBoxItem> 。该类如下所示,您可以清楚地看到有一个公共(public)属性 Value 和一个公共(public)属性 Text:

[Serializable]
public class CheckboxItem
{
    public string Text { get; set; }
    public string Value { get; set; }

    public CheckboxItem(string value, string text)
    {
        Value = value;
        Text = text;
    }

    public override string ToString()
    {
        return "brompot";
    }
}

但由于某种原因,每个复选框的文本和值使用 CheckBoxItem 类的 ToString() 方法,而不是适当的属性“Value”和“Text”。

PS:我检查了 checkboxitems 对象的值和文本不是字符串“brompot”...

让 toString() 方法返回文本或值不是一个选项,因为我希望复选框值是 value 属性和复选框(标签)文本

最佳答案

我进行了快速测试,这似乎按预期工作。 您能否提供更多详细信息?另外,验证我提供的代码是否与您正在执行的代码相似?

<div>
    <asp:Button ID="btnBind" runat="server" Text="Bind" OnClick="btnBind_Click" />
    <asp:CheckBoxList ID="cbList" runat="server"></asp:CheckBoxList>
</div>


public partial class _Default : Page
{
    protected void btnBind_Click(object sender, EventArgs e)
    {
        List<CheckboxItem> listCheckboxItems = new List<CheckboxItem>();
        listCheckboxItems.Add(new CheckboxItem("Val-1", "Item-1"));
        listCheckboxItems.Add(new CheckboxItem("Val-2", "Item-2"));
        listCheckboxItems.Add(new CheckboxItem("Val-3", "Item-3"));
        listCheckboxItems.Add(new CheckboxItem("Val-4", "Item-4"));
        listCheckboxItems.Add(new CheckboxItem("Val-5", "Item-5"));

        this.cbList.DataSource = listCheckboxItems;
        this.cbList.DataValueField = "Value";
        this.cbList.DataTextField = "Text";
        this.cbList.DataBind();
    }
}

[Serializable]
public class CheckboxItem
{
    public string Text { get; set; }
    public string Value { get; set; }

    public CheckboxItem(string value, string text)
    {
        Value = value;
        Text = text;
    }

    public override string ToString()
    {
        return "brompot";
    }
}

enter image description here

关于c# - CheckboxList 忽略 DataValueField 和 DataTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023639/

相关文章:

c# - 使用 Request.Form 确定在 CheckBoxList 中选择了哪些项目

asp.net - 如何在asp.net中查找复选框列表是否被选中

c# - 可靠的发布/订阅

c# - invalidate 方法有什么作用?

json - 如何在 flutter 中使用 Json 添加带有复选框列表图 block 的多个展开图 block

php - 如何使用 jQuery 提交函数将表单选中的复选框作为数组传递到 PHP 页面?

mysql - 从mysql加载数据到CheckBoxList Vb.net

c# - 一对多投影 LINQ 查询重复执行

c# - 10 秒后从控制台 (C#) 打开网页

c# - PayPal SOAP API 响应需要手动解析