ASP.NET: ListBox数据源和数据绑定

4

我在 .aspx 页面上有一个空的列表框

lstbx_confiredLevel1List

我在程序中生成了两个列表

List<String> l1ListText = new List<string>(); //holds the text 
List<String> l1ListValue = new List<string>();//holds the value linked to the text

我想在.aspx页面上加载lstbx_confiredLevel1List列表框和上述数值及文本。所以我正在进行以下操作:

lstbx_confiredLevel1List.DataSource = l1ListText;
lstbx_confiredLevel1List.DataTextField = l1ListText.ToString();
lstbx_confiredLevel1List.DataValueField = l1ListValue.ToString();
lstbx_confiredLevel1List.DataBind();

但是它没有使用l1ListText和l1ListValue加载lstbx_confiredLevel1List。有什么想法吗?
3个回答

11

你为什么不使用与DataSource相同的集合?它只需要具有用于键和值的两个属性。例如,您可以使用Dictionary<string, string>

var entries = new Dictionary<string, string>();
// fill it here
lstbx_confiredLevel1List.DataSource = entries;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();

您还可以使用匿名类型或自定义类。

假设您已经拥有这些列表并且需要将它们用作数据源。您可以即兴创建一个Dictionary

Dictionary<string, string> dataSource = l1ListText
           .Zip(l1ListValue, (lText, lValue) => new { lText, lValue })
           .ToDictionary(x => x.lValue, x => x.lText);
lstbx_confiredLevel1List.DataSource = dataSource;

谢谢,我正在使用C#,但是Dictionary给我编译器错误,我应该使用哪个库来消除这个错误? - user1889838
@user1889838: using System.Collections.Generic; 而在第二种方法中使用 ToDictionary 你还需要 using System.Linq; - Tim Schmelter

1

你最好使用一本字典:

Dictionary<string, string> list = new Dictionary<string, string>();
...
lstbx_confiredLevel1List.DataSource = list;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();

0

很遗憾,DataTextFieldDataValueField并不是这样使用的。它们是当前数据源中正在绑定的项目应该显示的字段的文本表示。

如果您有一个同时包含文本和值的对象,您可以将其制作成列表,并像这样设置为数据源:

public class MyObject {
  public string text;
  public string value;

  public MyObject(string text, string value) {
    this.text = text;
    this.value = value;
  }
}

public class MyClass {
  List<MyObject> objects;
  public void OnLoad(object sender, EventArgs e) {
    objects = new List<MyObjcet>();
    //add objects
    lstbx.DataSource = objects;
    lstbx.DataTextField = "text";
    lstbx.DataValueField = "value";
    lstbx.DataBind();
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接