我发现了这个错误。它是如此显而易见:我没有将数据绑定(bind)到正确的复选框列表!我应该将数据绑定(bind)到filterONTYPElist,但我正在将数据绑定(bind)到filterONDATASETlist...复制粘贴错误,抱歉...
我有一个呈现如下的复选框列表:
这是处理数据绑定(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";
}
}
关于c# - CheckboxList 忽略 DataValueField 和 DataTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023639/