![](/img/trans.png)
[英]DataTextField and DataValueField properties of DropDownList
[英]CheckboxList ignores DataValueField and DataTextField
我发现了错误。 如此清晰可见:我没有将数据绑定到正确的复选框列表中! 我应该一直绑定到filterONTYPElist,但是我正在绑定到filterONDATASETlist ...复制粘贴错误,对不起...
我有一个呈现如下的复选框:
这是处理数据绑定的代码:
FilterOnTypeCheckboxList.DataSource = listCheckboxItems;
FilterOnDatasetCheckboxList.DataValueField = "Value";
FilterOnDatasetCheckboxList.DataTextField = "Text";
FilterOnTypeCheckboxList.DataBind();
我的数据源是一个list<CheckBoxItem>
。 该类如下所示,您可以清楚地看到有一个公共属性Value和一个公共属性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";
}
}
但是由于某些原因,每个复选框的文本AND值都使用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";
}
}
我相信您的错误是由于您的ToString()
方法。
编辑为以下内容,看看是否能解决您的问题:
[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 Text;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.