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

查看:25
本文介绍了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();

但它不会使用 l1ListTextl1ListValue 加载 lstbx_confiredLevel1List.

but it does not load the lstbx_confiredLevel1List with l1ListText and l1ListValue.

有什么想法吗?

推荐答案

为什么不用和DataSource一样的集合呢?它只需要具有键和值的两个属性.你可以使用 Dictionary<string, string>:

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.

假设您已经拥有这些列表并且需要将它们用作数据源.您可以即时创建 Dictionary:

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天全站免登陆