2012-12-14 44 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(); 
    } 
}