数据在列表框中没有绑定

时间:2015-04-21 04:06:49

标签: c# .net

数据存在于lstListSource中,但不具有约束力。

objLogEntries.Message.AppendLine("Bind ListBox with list started...");
listBoxControl.DataSource = lstListSource;
listBoxControl.DataTextField = strDataTextField;
listBoxControl.DataValueField = strDateValueField;
listBoxControl.DataBind();
objLogEntries.Message.AppendLine("Bind ListBox with list ended...");
Log.WriteTraceLog(objLogEntries);

它抛出异常:lstlnkSRAlias'(ID of listbox) has a SelectedValue which is invalid because it does not exist in the list of items

1 个答案:

答案 0 :(得分:1)

您未正确使用DataTextFieldDataValueField。它应该设置为您尝试绑定到的对象上的属性名称。类似的东西:

listBoxControl.DataSource = lstListSource;
listBoxControl.DataTextField = "Text";
listBoxControl.ValueMember = "Value";
listBoxControl.DataBind();

此外,如果正在刷新绑定,请在设置数据源之前清除列表:

listBoxControl.Items.Clear();
listBoxControl.SelectedIndex = -1;
listBoxControl.SelectedValue = null;
listBoxControl.ClearSelection();
listBoxControl.DataSource = lstListSource;

documentation

中有一个完整的例子