2

I have a List< Dictionary< string, string>>. In the ItemTemplate of my GridView I would like to bind to the values in the dictionary based on their keys.

<ItemTemplate>
    <tr class="gridRow">
        <table width="100%">
            <tr><td><%# Eval("Lastname") %>, <%# Eval("Firstname") %> </td></tr>
            <tr><td><%# Eval("Address") %></td><td><%# Eval("Zipcode") %></td><td><%# Eval("City") %></td></tr>
        </table>
    </tr>
</ItemTemplate>

Is there anyway to do this without using code behind? I want to only have to change the ItemTemplate when new keys in the dictionary are added.

MvdD
  • 22,082
  • 8
  • 65
  • 93
  • Where do those `Lastname`, `Firstname`, `Address` and `Zipcode` properties come from? – Etienne de Martel Jun 12 '11 at 17:33
  • Sorry, I should have made clear that this is what I intended to do, but is not working. I do not have properties, but keys and values in a dictionary. The solution HalfTrackMindMan gave works for me. – MvdD Jun 12 '11 at 21:24

2 Answers2

4
<%# ((Dictionary<string, string>)(Container.DataItem))["FirstName"] %>
Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68
0

It took me a second to see what you were doing. I would image you can do this, but there are much better constructs to use to bind when you need to actually evaluate the item being bound.

Regardless, the problem you are having is you have a key and a value, you do not have a "Firstname", "Lastname", etc. Yes, I know you have strings that havve those values, but they are not named the values. A Dictionary contains a key value pair.

My solution would be to put the data into a construct like a DataSet. Then you can bind according to the column name. I imagine you can properly cast out the key value pair and then get an item by name, but I have not tried it. I see HalfTrackMindMan, but I am not sure that will work in a declarative fashion. It is worth a try.

Gregory A Beamer
  • 16,870
  • 3
  • 25
  • 32
  • I guess that would work. However, it does require code behind, although that code should not have to change when new keys show up in the dictionary. HalfTrackMindMan already gave a working solution. – MvdD Jun 12 '11 at 21:32