2012-12-14 43 views
2

我有一个空的列表框的.aspx页面ASP.NET:列表框的数据源和数据绑定

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(); 

,但它不与l1ListTextl1ListValue加载lstbx_confiredLevel1List

任何想法?

回答

8

你为什么不使用相同的集合作为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; 
+0

感谢,使用C#男,这让我对编译器错误字典,我用什么库去除错误 – user1889838

+0

@ user1889838:'using System.Collections.Generic;'并且对于ToDictionary的第二种方法,您还需要'使用System.Linq;'。 –

1

你最好使用dictionnary:

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不习惯这样。它们是他们应该显示当前正在DataSource中进行数据绑定的项目的字段的文本表示形式。

如果你有这样的召开文本和值的对象,你会做它的一个列表并将其设置为数据源这样的:

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(); 
    } 
}