ASP.NET:列表框的数据源和数据绑定 [英] ASP.NET: Listbox datasource and databind

查看:262
本文介绍了ASP.NET:列表框的数据源和数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an empty listbox on .aspx page

lstbx_confiredLevel1List

我生成两个列表编程

I am generating two lists programatically

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 列表框中。所以,我做以下内容:

I want to load lstbx_confiredLevel1List list box on .aspx page with above values and text. So i am doing following:

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

但它不会加载 lstbx_confiredLevel1List l1ListText l1ListValue

任何想法?

推荐答案

你为什么不使用相同的集合作为数据源?它只是需要具有用于键和值的两个属性。你可以F.E.使用词典&LT;字符串,字符串&GT;

Why don't you use the same collection as DataSource? It just needs to have two properties for the key and the value. You could f.e. use a 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();

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

You can also use an anonymous type or a custom class.

假设你已经这些列表,你需要将它们用作数据源。您可以创建一个词典飞:

Assuming that you have already these lists and you need to use them as DataSource. You could create a Dictionary on the fly:

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

这篇关于ASP.NET:列表框的数据源和数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆