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

use*_*838 3 c# asp.net listbox

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

lstbx_confiredLevel1List
Run Code Online (Sandbox Code Playgroud)

我以编程方式生成两个列表

List<String> l1ListText = new List<string>(); //holds the text 
List<String> l1ListValue = new List<string>();//holds the value linked to the text
Run Code Online (Sandbox Code Playgroud)

我想lstbx_confiredLevel1List在.aspx页面上加载带有上述值和文本的列表框.所以我在做以下事情:

lstbx_confiredLevel1List.DataSource = l1ListText;
lstbx_confiredLevel1List.DataTextField = l1ListText.ToString();
lstbx_confiredLevel1List.DataValueField = l1ListValue.ToString();
lstbx_confiredLevel1List.DataBind();
Run Code Online (Sandbox Code Playgroud)

但它没有加载lstbx_confiredLevel1Listwith l1ListTextl1ListValue.

有任何想法吗?

Tim*_*ter 10

你为什么不使用同一个系列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();
Run Code Online (Sandbox Code Playgroud)

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

假设您已经有这些列表,并且需要将它们用作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;
Run Code Online (Sandbox Code Playgroud)