Jar*_*ban 9 c# asp.net data-binding namevaluecollection
我应该使用什么样的集合将NameValue集合转换为可绑定到GridView?直接做它不起作用.
aspx.cs中的代码
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
任何提示最受欢迎.谢谢.X.
你可以使用Dictionary <string,string>而不是NameValueCollection.由于Dictionary <T,T>实现了IEnumerable,你可以使用LINQ:
resultGV.DataSource = from item in nvpDictionary
select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
Run Code Online (Sandbox Code Playgroud)
[编辑]其实你可以直接使用Dictionary作为:
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
Run Code Online (Sandbox Code Playgroud)
如果它没有按您希望的方式映射键/值,您可以随时返回LINQ.LINQ还允许您将字段重命名为您想要的任何字段.
[编辑]如果您无法更改为使用Dictionary <T,T>,请在方法中将NameValueCollection的副本复制为字典并绑定到它.
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();
}
Run Code Online (Sandbox Code Playgroud)
如果你经常这么做,你可以编写一个扩展方法来转换为Dictionary,并使用它.
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();
}
Run Code Online (Sandbox Code Playgroud)
这有点棘手,因为枚举器只返回Keys.但是,您可以使用Container.DataItem获取Key值,然后查找NameValueCollection以获取值:
<asp:GridView id="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Key">
<ItemTemplate><%# Container.DataItem %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11093 次 |
最近记录: |