我应该使用哪种集合来将 NameValue 集合转换为可绑定(bind)到 GridView? 直接做是不行的。
aspx.cs 中的代码
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
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.
最佳答案
能否使用 Dictionary
resultGV.DataSource = from item in nvpDictionary
select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
[编辑] 实际上你可以直接使用字典:
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
如果它没有按照您希望的方式映射键/值,您可以随时返回到 LINQ。 LINQ 还允许您将字段重命名为您想要的任何名称。
[编辑] 如果您无法更改为使用 Dictionary
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();
}
如果你经常这样做,你可以写一个扩展方法来转换成一个字典,然后这样使用它。
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();
}
关于c# - 将 NameValueCollection 绑定(bind)到 GridView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/217356/