计算gridview(.net)数据源中的项目数

发布于 2024-12-07 04:34:27 字数 536 浏览 2 评论 0原文

我有一个 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 语句即可工作。

I have a GridView and bind a list to it:

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

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

Now in the process of databinding, I would like to access the total number of items in the datasource.

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

GridView.Rows or GridView.DataKeys is no help because the gridview is being built at this point. Of course, I could use items.Count() but I would prefer to access the underlying datasource directly.

Update

The solutions posted work without the OrderBy statement which I included later.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

﹏半生如梦愿梦如真 2024-12-14 04:34:27
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   var count = ((ICollection<T>)GridView.DataSource).Count;
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   var count = ((ICollection<T>)GridView.DataSource).Count;
}
鹊巢 2024-12-14 04:34:27

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

      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;

    }

I guess you could access the count of items by doing something like below:

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

Hope this Helps!!

Edit 1:

Added full method used.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

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

    }
她如夕阳 2024-12-14 04:34:27

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

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

With my update included, the items count can be accessed with

var count = ((IEnumerable<T>)GridView.DataSource).Count();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文