将字典绑定到中继器 [英] Bind dictionary to repeater
问题描述
我有一个字典对象
并且想将它绑定到一个中继器.但是,我不确定在 aspx
标记中放什么来实际显示键值对.没有抛出错误,我可以让它与 List
一起工作.如何让字典显示在中继器中?
I have a dictionary object <string, string>
and would like to bind it to a repeater. However, I'm not sure what to put in the aspx
markup to actually display the key-value pair. There are no errors thrown and I can get it to work with a List
. How do I get a dictionary to display in a repeater?
推荐答案
一个IDictionary
也是一个ICollection
>.
您需要绑定到类似(未经测试)的东西:
You need to bind to something like (untested):
((KeyValuePair<string,string>)Container.DataItem).Key
((KeyValuePair<string,string>)Container.DataItem).Value
请注意,物品返回的顺序是未定义的.对于小型字典,它们很可能会按插入顺序返回,但这并不能保证.如果您需要有保证的顺序,SortedDictionary
按键排序.
Note that the order in which the items are returned is undefined. They may well be returned in the insertion order for small dictionaries, but this is not guaranteed. If you need a guaranteed order, SortedDictionary<TKey, TValue>
sorts by key.
或者,如果您需要不同的排序顺序(例如按值),您可以创建一个 List
键值对,然后对其进行排序,然后绑定到排序列表.
Or if you need a different sort order (e.g. by value), you could create a List<KeyValuePair<string,string>>
of your key-value pairs, then sort it, and bind to the sorted list.
答案:我在标记中使用此代码来单独显示键和值:
Answer: I used this code in the markup to display the key and value individually:
<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Key") %>
<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Value") %>
这篇关于将字典绑定到中继器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!