简体   繁体   中英

How do I use Eval() to reference values in a SortedDictionary in an asp Repeater?

I thought I was clever to switch from the memory intensive DataView to SortedDictionary as a memory efficient sortable data structure. Now I have no idea how get the key and value out of the datasource in the <%# or Eval() expressions.

SortedDictionary<int, string> data = RetrieveNames();
rCurrentTeam.DataSource = data;
rCurrentTeam.DataBind();

<asp:Repeater ID="rNames" runat="server">
 <ItemTemplate>
  <asp:Label ID="lblName" runat="server" Text='<%# Eval("what?") %>' />
 </ItemTemplate>
</asp:Repeater>

Any suggestions?

Use either of these two options:

<%# Eval("Key") %>
<!-- or -->
<%# Eval("Value") %>

depending on whether you need the key or the value from the dictionary.

This makes sense if you think about how data binding works. Data binding is a process by which a control takes an enumerable sequence, iterates that sequence, and uses reflection to extract values from each item in the sequence based on properties that the item exposes.

Since SortedDictionary<TKey,TValue> implements the IEnumerable<KeyValuePair<TKey, TValue>> interface you know that the repeater will enumerate a sequence of KeyValuePair<TKey, TValue> objects, binding to each one in turn.

If you look at the properties that are exposed by the KeyValuePair<TKey,TValue> class you will see just two: Key and Value . Since they are public properties you can Eval them and the control will be able to extract the values that they encapsulate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM