ASP.NET: Listbox datasource and databind(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();
但它不会使用 l1ListText 和 l1ListValue 加载 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:列表框数据源和数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET:列表框数据源和数据绑定
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
