What kind of collection I should use to convert NameValue collection to be bindable to GridView? When doing directly it didn't work.
Code in aspx.cs
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
Code in aspx
<asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Key" />
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
Any tip most welcome. Thanks. X.
I find it best to use a StringDictionary for databinding & accessing key & value
If you have a nested
Repeater
(orGridView
too, I'm sure), you need to alter Mark Brackett's answer to look like this, or else you'll get a run-time error about not being able to find a control with the name of rpt.It's a little tricky, because the enumerator returns only the Keys. But, you can get the Key value with Container.DataItem, and then look up into the NameValueCollection to get the value:
Finally I used solution suggested in your extension implementation, but without extension itself.
maybe do some helper class that will be static and do the translation for me in one place instead of many. This extension is quite handy... :-)
Thanks. X.
Can you use Dictionary<string,string> instead of NameValueCollection. Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
[EDIT] Actually you may be able to use Dictionary directly as:
If it doesn't map key/value the way you want you can always go back to LINQ. LINQ would also allow you to rename the fields to whatever you want.
[EDIT] If you can't change to use Dictionary<T,T>, make a copy of the NameValueCollection as a Dictionary in the method and bind to it.
If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.
I had a similar problem involving binding a Dictionary (SortedDictionary really) to a GridView and wanting to rename the columns. What ended up working for me is some thing a little easier to read.
This works by taking the Container.DataItem, the current item the GridView is trying to display, coercing it into it's actual data type (KeyValuePair) and then displaying the desired property of that item.