问题描述
什么样的收藏我应该用转换NameValue集合是绑定到GridView的?
如果直接这样做没有工作。
What kind of collection I should use to convert NameValue collection to be bindable to GridView?When doing directly it didn't work.
code在aspx.cs
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
code在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>
任何提示深受欢迎。谢谢。 [X]。
Any tip most welcome. Thanks. X.
推荐答案
你能使用字典&LT;字符串,字符串&GT;而不是NameValueCollection中。因为字典&LT; T,T&GT;实现IEnumerable你可以使用LINQ像这样:
Can you use Dictionary<string,string> instead of NameValueCollection. Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
resultGV.DataSource = from item in nvpDictionary
select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
其实你可以使用词典直接作为:
Actually you may be able to use Dictionary directly as:
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
如果它不映射键/值你愿意,你可以随时返回到LINQ的方式。 LINQ也将允许您重命名字段到任何你想要的。
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.
如果你不能改变使用字典&LT; T,T&gt;中做出的NameValueCollection的副本作为一个字典的方法,并绑定到它
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.
private void BindList(NameValueCollection nvpList)
{
Dictionary<string,string> temp = new Dictionary<string,string>();
foreach (string key in nvpList)
{
temp.Add(key,nvpList[key]);
}
resultGV.DataSource = temp;
resultGV.DataBind();
}
如果你这样做了很多,你可以写一个扩展方法将转换为一个字典,并使用它如此。
If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.
public static class NameValueCollectionExtensions
{
public static Dictionary<string,string> ToDictionary( this NameValueCollection collection )
{
Dictionary<string,string> temp = new Dictionary<string,string>();
foreach (string key in collection)
{
temp.Add(key,collection[key]);
}
return temp;
}
}
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = nvpList.ToDictionary();
resultGV.DataBind();
}
这篇关于绑定到的NameValueCollection GridView的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!