【问题标题】:Count total rows of gridview with pagination用分页计算gridview的总行数
【发布时间】:2011-08-12 21:34:46
【问题描述】:

我有一个带分页的 GridView。当我尝试用 gridview.rows.count 计算 gridview 行时,它只给我当前页面的行数。

无论页面索引如何,如何获取 GridView 的总行数?

//这里是.aspx页面的代码

<%@ Page Title="Search candidates based on vacancy" Language="C#" MasterPageFile="~/HR     Department/hrmasterpage.master"
   AutoEventWireup="true" CodeFile="searcAppForVac.aspx.cs"     Inherits="HR_Department_searcAppForVac" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"       runat="Server">    <table width="100%">
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td align="center" class="tdtitle">
            Search Candidates
        </td>
    </tr>
    <tr>
        <td>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <table width="100%">
                        <tr>
                            <td class="RowHeight" width="20%">
                                Select Company
                            </td>
                            <td width="30%">
                                <asp:DropDownList ID="companyList" runat="server" AppendDataBoundItems="true" AutoPostBack="True"
                                    OnSelectedIndexChanged="companyList_SelectedIndexChanged" Width="150px">
                                    <asp:ListItem Text="-Select Company-" Value="-1"></asp:ListItem>
                                </asp:DropDownList>
                            </td>
                            <td width="20%">
                                Select Department
                            </td>
                            <td width="30%">
                                <asp:DropDownList ID="deptList" runat="server" AppendDataBoundItems="true" AutoPostBack="True"
                                    onclick="Validate();" OnSelectedIndexChanged="deptList_SelectedIndexChanged"
                                    Width="150px">
                                    <asp:ListItem Value="-1">-Select Department-</asp:ListItem>
                                </asp:DropDownList>
                            </td>
                        </tr>
                        <tr>
                            <td class="RowHeight" width="20%">
                                Select Vacancy
                            </td>
                            <td colspan="3" width="*">
                                <asp:DropDownList ID="vacanyList" runat="server" AppendDataBoundItems="true" 
                                    Width="200px" AutoPostBack="True" 
                                    onselectedindexchanged="vacanyList_SelectedIndexChanged">
                                    <asp:ListItem Value="-1">-Select Vacancy-</asp:ListItem>
                                </asp:DropDownList>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" align="center">
                                &nbsp;
                                <asp:Label ID="notifyLbl" runat="server" Font-Size="Large" ForeColor="Red" 
                                    Text="Label"></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <asp:Label ID="titleLbl" runat="server" Font-Size="Large" ForeColor="Red" 
                                    Text="Label"></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <asp:GridView ID="appForVacGrid" runat="server" AutoGenerateColumns="False" 
                                CellPadding="4" ForeColor="#333333" AllowPaging="True" 
                                    onpageindexchanging="appForVacGrid_PageIndexChanging" GridLines="None" 
                                    PageSize="3">
                                    <RowStyle BackColor="#EFF3FB" />
                                    <Columns>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                App.ID
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="appIdLbl" runat="server" Text='<%# Eval("AppId") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                First Name
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="firstNameLbl" runat="server" Text='<%# Eval("AppFirstName") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                Last Name
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="lastNameLbl" runat="server" Text='<%# Eval("AppLastName") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                Qualification
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="qualiNameLbl" runat="server" Text='<%# Eval("QualiName") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                &nbsp;Experience
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("TotalExpYear") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                EmailId
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Label ID="emailLbl" runat="server" Text='<%# Eval("AppEmailId1") %>'></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <HeaderTemplate>
                                                Send Mail
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:CheckBox ID="sendMailBox" runat="server" />
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                    </Columns>
                                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" 
                                        HorizontalAlign="Right" />
                                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" 
                                        VerticalAlign="Top" />
                                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" 
                                        Font-Size="Medium" HorizontalAlign="Left" />
                                    <EditRowStyle BackColor="#2461BF" />
                                    <AlternatingRowStyle BackColor="White" />
                                </asp:GridView>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" align="center">
                                &nbsp;
                            </td>
                        </tr>
                        <tr>
                            <td align="center" colspan="4">
                                <asp:Button ID="sendMailBtn" runat="server" Height="40px" Text="SEND MAIL" 
                                    Width="100px" onclick="sendMailBtn_Click" />
                            </td>
                        </tr>
                        <tr>
                            <%--<td>
                                &nbsp;
                            </td>--%>
                        </tr>
                    </table>
                </ContentTemplate>
                <Triggers>
                <asp:AsyncPostBackTrigger ControlID="companyList" EventName="SelectedIndexChanged" />
                <asp:AsyncPostBackTrigger ControlID="deptList" EventName="SelectedIndexChanged" />
                <asp:AsyncPostBackTrigger ControlID="appForVacGrid" EventName="pageindexchanged" />
                </Triggers>
              </asp:UpdatePanel>

        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
</table>

<script type="text/javascript">
    function alertOnBadSelection() {
        var select = document.getElementById('companyList');
        if (select.options[select.selectedIndex].value == "-Select Company-") {
            alert('Please Select Company!');
            return false;
        }
    }    
</script>

// 这是我的 aspx.cs 页面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

public partial class HR_Department_searcAppForVac : System.Web.UI.Page
{
DataOperation oDo = new DataOperation();
AppVacancyDetailClass objAppVacDetail = new AppVacancyDetailClass();
protected void Page_Load(object sender, EventArgs e)
{
    notifyLbl.Visible = false;
    titleLbl.Visible = false;
    sendMailBtn.Visible = false;
    try
    {
        if (!IsPostBack)
        {
            // Disable department dropdown list and vacancy dropdown list till company is not selected.
            deptList.Enabled = false;
            vacanyList.Enabled = false;
            //Fill Company dropdown list.
            DataTable objCmpnyTable = oDo.DropDownList("select * from tblCompanyMaster");
            if (objCmpnyTable.Rows.Count > 0)
            {
                companyList.DataSource = objCmpnyTable;
                companyList.DataValueField = "CompId";
                companyList.DataTextField = "CompName";
                companyList.DataBind();
            }
            else
            {
                notifyLbl.Visible = true;
                notifyLbl.Text = "There is not any company in the list.";
            }
        }
        else
        {
            if (companyList.SelectedIndex <= 0)
            {
                //Disable department dropdown list and vacancy dropdown list till company is not selected.
                deptList.Enabled = false;
                vacanyList.Enabled = false;
            }
        }
     }
     catch (Exception)
     {
          throw;
     }
 }
protected void companyList_SelectedIndexChanged(object sender, EventArgs e)
{
    //Disable vacancy dropdown list till depratment list is not selected
    vacanyList.Enabled = false;
    appForVacGrid.DataSource = null;
    appForVacGrid.DataBind();
    try
    {
        if (companyList.SelectedIndex > 0)
        {
            deptList.Enabled = true;
            deptList.Items.Clear();
            string str = "select * from vwCompWiseList where CompId=" + companyList.SelectedValue;
            DataTable objDeptTable = oDo.DropDownList("select DeptId,DeptName from vwCompWiseDept where CompId= "+companyList.SelectedValue);
            if (objDeptTable.Rows.Count > 0)
            {
                deptList.DataSource = objDeptTable;
                deptList.DataTextField = "DeptName";
                deptList.DataValueField = "deptId";
                deptList.DataBind();
                deptList.Items.Insert(0, new ListItem("--Select Department--", "-1"));
            }
            else 
            {
                deptList.Items.Insert(0, new ListItem("--No Departments--", "-1"));
                notifyLbl.Visible = true;
                notifyLbl.Text = "No Departments Available in " + companyList.SelectedItem.Text;
            }
        }
        else
        {
            notifyLbl.Visible = true;
            notifyLbl.Text = "Select Company....";
            appForVacGrid.DataSource = null;
            appForVacGrid.DataBind();
        }
    }
    catch (Exception)
    {

        throw;
    }    
}
protected void deptList_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (deptList.SelectedIndex > 0)
        {
            vacanyList.Enabled = true;
            vacanyList.Items.Clear();
            DataTable objVacancytbl = oDo.DropDownList("select VacId,VacTitle from tblVacancyMaster where DeptId =" + deptList.SelectedValue + " and CompId=" + companyList.SelectedValue);
            if (objVacancytbl.Rows.Count > 0)
            {
                vacanyList.DataSource = objVacancytbl;
                vacanyList.DataValueField = "VacId";
                vacanyList.DataTextField = "VacTitle";
                vacanyList.DataBind();
                vacanyList.Items.Insert(0, new ListItem("--Select Vacancy--", "-1"));
                appForVacGrid.DataSource = null;
                appForVacGrid.DataBind();
            }
            else
            {
                notifyLbl.Visible = true;
                notifyLbl.Text = "ALL VACANCIES ARE CLOSED IN "+" "+deptList.SelectedItem.Text.ToUpper();
                vacanyList.Enabled = false;
                appForVacGrid.DataSource = null;
                appForVacGrid.DataBind();
            }
        }
        else
        {
            notifyLbl.Visible = true;
            notifyLbl.Text = "Select Department...";
            appForVacGrid.DataSource = null;
            appForVacGrid.DataBind();
            vacanyList.Enabled = false;
        }
    }
    catch (Exception)
    {            
        throw;
    }
}
protected void vacanyList_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        DataTable AppListTbl = objAppVacDetail.GetValue("CompId=" + companyList.SelectedValue + " and DeptId=" + deptList.SelectedValue + " and VacId=" + vacanyList.SelectedValue);
        if (AppListTbl.Rows.Count > 0)
        {
            appForVacGrid.DataSource = AppListTbl;
            appForVacGrid.DataBind();
            appForVacGrid.Columns[5].Visible = false;
            Session.Add("snAppListTbl", AppListTbl);
            titleLbl.Visible = true;
            titleLbl.Text = AppListTbl.Rows.Count.ToString() + " " + "CANDIDATE(S) ARE ELIGIBLE FOR THE POST OF" + " " + vacanyList.SelectedItem.Text.ToUpper() + ".";
            sendMailBtn.Visible = true;
        }
        else
        {
            notifyLbl.Visible = true;
            notifyLbl.Text = "ALL VACANCIES ARE CLOSED IN " + " " + deptList.SelectedItem.Text.ToUpper();
            appForVacGrid.DataSource = null;
            appForVacGrid.DataBind();
        }
    }
    catch (Exception)
    {

        throw;
    }
}
protected void appForVacGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    //DataTable AppListTbl = (DataTable)Session["snAppListTbl"];
    titleLbl.Visible = true;
    titleLbl.Text = ((DataTable)Session["snAppListTbl"]).Rows.Count.ToString() + " " + "CANDIDATE(S) ARE ELIGIBLE FOR THE POST OF" + " " + vacanyList.SelectedItem.Text.ToUpper() + ".";
    appForVacGrid.PageIndex = e.NewPageIndex;
    appForVacGrid.DataSource = (DataTable)Session["snAppListTbl"];
    appForVacGrid.DataBind();
    sendMailBtn.Visible = true;
}
protected void sendMailBtn_Click(object sender, EventArgs e)
{
    DataTable AppListTable = ((DataTable)Session["snAppListTbl"]);
    int intTotalRows = AppListTable.Rows.Count;
    string strFromId="",strToId="",strCcId="",strBccId="";
    string strVacTitle="",strCompName="",strMailBody="";
    string strSubject = "Rgarding Selection of Your Resume";
    Label EmailLbl;
    //for (int intRow = 0; intRow < intTotalRows; intRow++)
    foreach (GridViewRow Row in appForVacGrid.Rows)
    {
        CheckBox objSendMail = (CheckBox)Row.FindControl("sendMailBox");
        //CheckBox objSendMail = (CheckBox)appForVacGrid.Rows[Row].FindControl("sendMailBox");
        if (objSendMail.Checked)
        {
            if (strToId == "")
            {
                //strToId = AppListTable.Rows[Row]["AppEmailId1"].ToString();
                EmailLbl = (Label)Row.FindControl("emailLbl");
                strToId = EmailLbl.Text;
            }
            else
            {
                //strToId += "," + AppListTable.Rows[Row]["AppEmailId1"].ToString();
                EmailLbl = (Label)Row.FindControl("emailLbl");
                strToId +=","+ EmailLbl.Text;
            }
        }
    }
    strVacTitle = AppListTable.Rows[intTotalRows]["VacTitle"].ToString();
    strCompName = AppListTable.Rows[intTotalRows]["CompName"].ToString();
    strMailBody = CommonProcedures.GetMailBody(strVacTitle, strCompName);
    //CommonProcedures.SendMail(strFromId, strToId, strCcId, strBccId, strSubject, null, strMailBody, false);
}
}

现在我想向所有选中复选框的候选人发送邮件.. 我尝试了很多东西,但没有得到任何解决方案

【问题讨论】:

  • 试试这个appForVacGrid.AllowPaging = false; appForVacGrid.DataBind(); // 编写发送邮件的代码 appForVacGrid.AllowPaging = true; appForVacGrid.DataBind();
  • @Mukesh.. 这样做有什么好处???我试过这个,但它没有任何区别。我想从不同的页面中选择复选框,邮件应该一键发送到选中复选框的所有行....

标签: c# asp.net gridview


【解决方案1】:

如果您使用 sqldatasource 或 objectdatasource 您需要在处理数据源的 Selected 事件时使用 ObjectDataSourceStatusEventArgs 或 SqlDataSourceStatusEventArgs 的 ReturnValue。

如果您使用的是 sqldatasource,您可以使用在选择操作完成后触发的 'Selected' 事件来计算总行数。

protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
  int rowCount = e.AffectedRows;
}  

如果您使用对象数据源,请务必注意 ODS 上的 Selected 事件会被调用两次,一次是返回数据集,一次是调用您在 SelectCountMethod 属性中指定的方法。简单测试一下返回是否是事件中的 Int32。

protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
    if (e.ReturnValue.GetType() == typeof(System.Int32))
        int rowCount = (Int32)e.ReturnValue;
}  

您可以在以下位置找到一个工作示例:http://www.webswapp.com/codesamples/aspnet20/dropdownlist_gridview/default.aspx

如果您的 GridView 被 DataSet 或 DataTable 填充:

int rowCount=((DataTable)Customer).Rows.Count;

如果您要绑定对象列表或数组,则可以执行以下操作:

int rowCount = ((Customer[])gv.DataSource).Count;

【讨论】:

    【解决方案2】:

    是的,没错,它只会返回当前页面行。如果您真的想获取总行数,则需要从您的数据源中获取。

    就像...如果你有 DataTable 那么它会像...

    DataTable.Rows.Count
    

    【讨论】:

    • @Muhammad Akhtar。我用 datatable.rows.count 得到了总行数。现在,如果我想操作第一页的所有行,我该怎么做???
    • 您需要迭代所有行。 foreach(grid.Rows 中的 GridViewRow 行)
    • @Muhammad Akhtar。我想迭代 gridview 行,并且对于每一行我想从数据表中获取该 perticluar 行的值,这是 foreach() 无法实现的
    • @Muhammad Akhtaar..foreach() 也只给出当前页面的行。它没有给出所有行的gridview
    • 然后你可以迭代你的数据源;
    【解决方案3】:

    是的,我认为使用 PagedDataSource 是一个更好的选择。我正在使用它。

    PagedDataSource pds = new PagedDataSource();
    pds.DataSource = dt_main.DefaultView;
    pds.AllowPaging = true;
    pds.PageSize = 8;
    
    int currentPage;
    
    if (Request.QueryString["page"] != null)
    {
        currentPage = Int32.Parse(Request.QueryString["page"]);
    }
    else
    {
        currentPage = 1;
    }
    
    pds.CurrentPageIndex = currentPage - 1;
    Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
    
    if (!pds.IsFirstPage)
    {
        linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
    }
    
    if (!pds.IsLastPage)
    {
        linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
    }
    gridMain.DataSource = pds;
    gridMain.DataBind();
    

    【讨论】:

    • @Mukesh .... 我的问题是我在 grieview 的模板字段中有复选框。我想从 gridview 中检索所有复选框,并基于该复选框我想从数据表中获取记录。用你的方式不可能……还有其他出路吗???
    • “我想从 gridview 中检索所有复选框,并基于该复选框我想从数据表中获取记录”这条线有点混乱。你能发布你的代码,然后我可以很容易地帮助你。
    【解决方案4】:

    试试下面的代码

    int _TotalRecs = ((System.Data.DataView)GridView.DataSource).Count;
    int _CurrentRecStart = GridView.PageIndex * GridView.PageSize + 1;
    int _CurrentRecEnd = GridView.PageIndex * GridView.PageSize + GridView.Rows.Count;
    
    lblTitle.Text = string.Format("Displaying {0} to {1} of {2} records found", _CurrentRecStart, _CurrentRecEnd, _TotalRecs);
    

    例如输出将如下所示....

    显示找到的 67 条记录中的 1 到 15 条。

    【讨论】:

    • 短而有效.. 很好的解决方案.. 谢谢
    【解决方案5】:

    您可以使用分页数据源来绑定gridview,这样自定义分页和获取页数将非常容易。

    【讨论】:

    • parogrammer.. 但我没有任何分页数据源。我有包含所有gridview 行的数据表。根据页面大小,其中只有部分行在 gridview 中可见。当我使用 datatable.rows.count 循环遍历 girdview 时,它会在当前页面后抛出错误。无论数据源或数据表如何,有什么方法可以获取当前页数。如果可以通过数据表实现,那么如何使用数据表获取当前页面的行数??
    • @Chirag Fanse:它会引发异常,因为您没有回发数据。将DataTable.Rows.Count() 存储在会话变量中以将其保留在回发中。
    • 如果您已经绑定到数据表,那么您可以使用 DataTable.Rows.Count 来获取行数。如果您对使用分页数据源感兴趣,它是用于自定义绑定,这就是我告诉您的原因。请查看链接。 forums.asp.net/t/1451791.aspx
    【解决方案6】:
                if (Grid.DataSource == null)
                    return 0;
                else if (Grid.DataSource.GetType() == typeof(DataTable))
                    return (Grid.DataSource as DataTable).Rows.Count;
                else if (Grid.DataSource.GetType().IsGenericType)
                    return (Grid.DataSource as IList).Count;
    

    【讨论】:

      【解决方案7】:

      尝试 (gridView.DataSource as IEnumerable).Count() 用于主集合

      【讨论】:

        【解决方案8】:

        这样

        (gridview1.DataSource as DataTable).Rows.Count();
        

        【讨论】:

        • 欢迎来到 Stack Overflow!您是否会考虑添加一些叙述来解释为什么此代码有效,以及是什么使它成为问题的答案?这对提出问题的人以及其他任何出现的人都非常有帮助。
        【解决方案9】:

        如果您使用数据表或其他数据源进行绑定,则可以显示数据源中的总记录。 例如

          if (dtLog != null && dtLog .Rows.Count >= 0)
                    {
                        lblTotal.Text = "Total " + Convert.ToString(dtLog .Rows.Count) + " records.";
                    }
        

        【讨论】:

          【解决方案10】:
          <font-color='red'><b>dim dt as datatable<Br>
          dt=gridview1.datasource<br>
          msgbox (dt.rows.count)<b></font>
          

          【讨论】:

          • 欢迎来到 Stack Overflow!除了代码之外,请考虑在您的答案中添加解释。
          • 请仔细检查以确保代码符合预期。
          【解决方案11】:

          如果您有一个gridview,它将使用datatabledataset 填充,然后计算datatabledataset (ds.table(0).rows.count) 例如

          For cnt1 = 0 To Total_batchRecords - 1
             dgchgsdtl1.Rows.Item(cnt1).FindControl("ControlName"), Label)
          Next
          

          【讨论】:

            【解决方案12】:
                           int a = grdvw.PageIndex;
                           int rowcount=0;
            
                            for (int i = 0; i < grdvw.PageCount; i++)
                            {
                                grdvw.SetPageIndex(i);
                                foreach (GridViewRow row in grdvw.Rows)
                                {
                                    if (row.RowType == DataControlRowType.DataRow)
                                    {
                                      rowcount++;
                                    }
                                }
                           }
            
                         grdvw.SetPageIndex(a);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-02-16
              • 2021-03-20
              • 1970-01-01
              • 2011-04-14
              • 2010-09-06
              • 2015-12-20
              • 1970-01-01
              相关资源
              最近更新 更多