C# 如何获取GridView的DataSource中的记录数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15129665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:09:37  来源:igfitidea点击:

How to get the count of records in the DataSource of the GridView

c#asp.net.net

提问by Adham

I have a grid viewalready binded with model, Now I want to get the count of the rows in this GridView's Datatable? not on the page count.

grid view已经绑定了模型,现在我想获取其中的行数GridView's Datatable?不在页数上。

采纳答案by Habib

You can convert the GridView's DataSource to DataTable or DataView and then count the rows.

您可以将 GridView 的 DataSource 转换为 DataTable 或 DataView,然后计算行数。

DataTable dt = (DataTable) gridView.DataSource; 
int count = dt.Rows.Count;

But this will be available only at the time of binding, not across the postback.

但这仅在绑定时可用,而不是在回发时可用。

To get the row count on post back, you can store the DataTableor its row count in session before binding it to the GridView.

要在回发时获取行数,您可以在将DataTable其绑定到 GridView 之前将其或它的行数存储在会话中。

DataTable dt = GetDataSourceTable();
Session["RowsCount"] = dt.Rows.Count;
Session["DataTable"] = dt; //Should be avoided since session are per user. 
gridView.DataSource = dt;
gridView.DataBind();

Later you can access the Countfrom the session.

稍后您可以Count从会话中访问。

回答by ????

You can cast datasource in collection and then count as follow

您可以在集合中转换数据源,然后按如下方式计算

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

Or if you have datatable as source then

或者如果你有数据表作为源然后

DataTable dt = gridView.DataSource as DataTable; 
 int count = dt.Rows.Count;

回答by Aaron Blenkush

Have you tried something like the following?

您是否尝试过类似以下的操作?

yourDataTable.Rows.Count();

回答by nirbhay

You can try this:

你可以试试这个:

textBox1.Text = gridView1.RowCount.ToString();

回答by mahdi roodbari

you can use this code:

您可以使用此代码:

DataView MyDV = (DataView)SqldatasourceName.Select(DataSourceSelectArguments.Empty);
MyDV.RowFilter = SqldatasourceName.FilterExpression;
int RecordCount = MyDV.Count;