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

时间:2012-12-14 13:05:31

标签: c# asp.net listbox

我在.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();

但它没有加载lstbx_confiredLevel1List l1ListTextl1ListValue

有什么想法吗?

3 个答案:

答案 0 :(得分:10)

为什么不使用与DataSource相同的集合?它只需要有两个属性作为键和值。你可以f.e.使用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();

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

假设您已经拥有这些列表,并且需要将它们用作DataSource。您可以动态创建Dictionary

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

答案 1 :(得分:1)

你最好使用一个词典:

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

答案 2 :(得分: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();
  }
}
相关问题