c# - 将 NameValueCollection 绑定(bind)到 GridView?

标签 c# asp.net data-binding namevaluecollection

我应该使用哪种集合来将 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 代替 NameValueCollection。由于 Dictionary 实现了 IEnumerable,您可以这样使用 LINQ:

resultGV.DataSource = from item in nvpDictionary
                      select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();

[编辑] 实际上你可以直接使用字典:

resultGV.DataSource = nvpDictionary;
resultGV.DataBind();

如果它没有按照您希望的方式映射键/值,您可以随时返回到 LINQ。 LINQ 还允许您将字段重命名为您想要的任何名称。

[编辑] 如果您无法更改为使用 Dictionary,请在方法中将 NameValueCollection 复制为一个 Dictionary 并绑定(bind)到它。

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/

相关文章:

javascript - 从 asp 下拉列表调用 Javascript 函数

c# - 如何确定哪个 EndPoint 导致错误代码 10054 的 SocketException? ("An existing connection was forcibly closed by the remote host.")

c# - 嵌套的 xaml 元素 - 在代码中重写它

xaml - XAML 中的字符串格式

c# - 使用 WPF 和 C# 进行嵌套数据绑定(bind)

c# - Visual Studio 2019 WPF 设计器不会显示自定义控件

ASP.NET MVC : Adding selected CSS class to ActionLink if url matches current url

c# - 如何在特定 <div> 标记中的另一个 aspx 页面中加载一个 aspx 页面

c# - 无法使用 ContentTypeReader 加载模型

c# - 无法在桌面应用程序后面的代码中绑定(bind) GridView