Csharp/C#教程:将NameValueCollection绑定到GridView?分享


将NameValueCollection绑定到GridView?

我应该使用什么样的集合将NameValue集合转换为可绑定到GridView? 直接做它不起作用。

aspx.cs中的代码

private void BindList(NameValueCollection nvpList) { resultGV.DataSource = list; resultGV.DataBind(); } 

aspx中的代码

       

任何提示最受欢迎。 谢谢。 X。

你可以使用Dictionary 而不是NameValueCollection。 由于Dictionary 实现了IEnumerable,你可以使用LINQ:

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

[编辑]实际上你可以直接使用Dictionary作为:

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

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

[编辑]如果您无法更改为使用Dictionary ,请在方法中将NameValueCollection的副本复制为字典并绑定到它。

 private void BindList(NameValueCollection nvpList) { Dictionary temp = new Dictionary(); foreach (string key in nvpList) { temp.Add(key,nvpList[key]); } resultGV.DataSource = temp; resultGV.DataBind(); } 

如果你这么做了,你可以编写一个扩展方法来转换为Dictionary,并使用它。

 public static class NameValueCollectionExtensions { public static Dictionary ToDictionary( this NameValueCollection collection ) { Dictionary temp = new Dictionary(); foreach (string key in collection) { temp.Add(key,collection[key]); } return temp; } } private void BindList(NameValueCollection nvpList) { resultGV.DataSource = nvpList.ToDictionary(); resultGV.DataBind(); } 

这有点棘手,因为枚举器只返回Keys。 但是,您可以使用Container.DataItem获取Key值,然后查找NameValueCollection以获取值:

    <%# Container.DataItem %>    <%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %>     

最后,我使用了扩展实现中建议的解决方案,但没有扩展本身。

  private void BindList(NvpList nvpList) { IDictionary dict = new Dictionary(); foreach (String s in nvpList.AllKeys) dict.Add(s, nvpList[s]); resultGV.DataSource = dict; resultGV.DataBind(); } 

也许做一些静态的帮助类,并在一个地方而不是很多地为我做翻译。 这个扩展非常方便…… ?

谢谢。 X。

如果你有一个嵌套的Repeater (或GridView ,我也很确定),你需要改变Mark Brackett的答案看起来像这样,否则你会得到一个关于无法找到控件的运行时错误rpt的免费精选名字大全。

   
  • <%# Container.DataItem %>: <%# ((NameValueCollection)((Repeater)Container.Parent).DataSource)[(string)Container.DataItem] %>
  • 我发现最好使用StringDictionary进行数据绑定和访问键和值

     Dim sDict as New StringDictionary sDict.Add("1","data1") sDict.Add("2","data2") sDict.Add("3","data3") ... CheckBoxList1.DataSource = sDict CheckBoxList1.DataValueField = "key" CheckBoxList1.DataTextField = "value" CheckBoxList1.DataBind() 

    我有一个类似的问题涉及将Dictionary(真正的SortedDictionary)绑定到GridView并想要重命名列。 最终为我工作的是一些更容易阅读的东西。

         <%# ((KeyValuePair)Container.DataItem).Key %>     <%# ((KeyValuePair)Container.DataItem).Value %>     

    这是通过获取Container.DataItem(GridView尝试显示的当前项),将其强制转换为实际数据类型(KeyValuePair)然后显示该项的所需属性来实现的。

    上述就是C#学习教程:将NameValueCollection绑定到GridView?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

    本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

    ctvol管理联系方式QQ:251552304

    本文章地址:https://www.ctvol.com/cdevelopment/955264.html

    (0)
    上一篇 2021年11月21日
    下一篇 2021年11月21日

    精彩推荐