【问题标题】:Count items in datasource of gridview (.net)计算gridview(.net)数据源中的项目
【发布时间】:2011-11-27 01:13:09
【问题描述】:

我有一个 GridView 并将一个列表绑定到它:

List<T> items = T.GetItems();

GridView.DataSource = items.OrderBy(x => x.SomeValue);
GridView.DataBind();

现在在数据绑定过程中,我想访问数据源中的项目总数。

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //access total number of datasource items
}

GridView.Rows 或 GridView.DataKeys 无济于事,因为此时正在构建 gridview。当然,我可以使用 items.Count(),但我更愿意直接访问底层数据源。

更新

发布的解决方案没有我稍后包含的 OrderBy 语句。

【问题讨论】:

    标签: .net gridview count datasource


    【解决方案1】:
    protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       var count = ((ICollection<T>)GridView.DataSource).Count;
    }
    

    【讨论】:

    • 我收到一个错误(尝试翻译):“System.Linq.OrderedEnumerable2[T,System.String] cannot be cast to type "System.Collections.Generic.ICollection1[T] 类型的对象”
    • 那么您使用List&lt;T&gt;,就像您在问题中所说的那样。如果您使用的是 Linq2Sql 数据源,请尝试在语句末尾添加 ToList()
    【解决方案2】:

    我想您可以通过执行以下操作来访问项目数:

          int count = (GridView1.DataSource as List<T>).Count;
    

    希望这有帮助!

    编辑 1:

    添加了使用的完整方法。

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
    
            int count = (GridView1.DataSource as List<string>).Count;
    
        }
    

    【讨论】:

    • 不,我收到一个错误:“对象引用未设置为对象实例”
    • 这里,“GridView1”是我使用的网格的 ID。在此处提供您的 ID,“T”是您尝试绑定的列表类型。如果这对我有用,请告诉我。
    • 它不起作用。我已将所有内容更改为我的控件和类型。你能显示你的总代码吗?现在将退出。
    【解决方案3】:

    包含我的更新后,可以使用以下方式访问项目计数

    var count = ((IEnumerable<T>)GridView.DataSource).Count();
    

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多