在网格视图中使用分页搜索btn

时间:2016-05-12 07:56:15

标签: c# asp.net gridview

我已经创建了gridview with paging并在gridview中搜索数据。如果你在gridview中过滤数据它有成功显示带有分页的结果,我有数据的数量和页数。显示后,我将点击下一页,因为gridview每页只显示10条记录,但我已经过滤了10条以上的记录,因此它将以页面方式显示。然后当我点击下一页gridview将从数据库加载整个数据并显示但我想在搜索数据时只显示过滤记录。 aspx代码低于

<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
            <asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
                <HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
                <AlternatingRowStyle BackColor="#D4EFFD" />
                <PagerSettings  Position="Top" />
                <PagerStyle Height="8px" HorizontalAlign="Center"  />
                <PagerTemplate>
                    <table align="center" style="width: 100%;"  cellpadding="0" cellspacing="0" border="0">
                        <tr>
                            <td align="center" style="width: 60%;">
                                <table align="center" width="50%">
                                    <tr>
                                        <td>
                                            <asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
                                        </td>

                                        <td>
                                            <asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
                                        </td>
                                        <td style="    width: 8%;">
                                            <asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
                                            <asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
                                            </asp:DropDownList>
                                        </td>
                                        <td>
                                            <asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
                                        </td>
                                        <td>
                                            <asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
                                        </td>
                                    </tr>
                                </table>
                            </td>

                        </tr>
                    </table>
                </PagerTemplate>
                <Columns>
                    <asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
                    <asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
                    <asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
                    <asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
                    <asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
                    <asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
                    <asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
                    <asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
                        <ItemTemplate>
                            <a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
                                <img src="<%#Eval("schedule1") %>" alt="" />
                            </a>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
                        <ItemTemplate>
                            <asp:ImageButton ID="lnkDuplicate" runat="server"
                                ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
                        <ItemTemplate>
                            <asp:ImageButton ID="lnkBtnContinue" runat="server"
                                ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
                        <ItemTemplate>
                            <asp:ImageButton ID="imgBtnDel" runat="server"
                                ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>

            </asp:GridView>

和aspx.cs代码低于

  protected void Search_Click(object sender, EventArgs e)
    {
        this.BindGrid();
    }
    private void BindGrid()
    {
        try
        {
            if (txtsearch.Text != "")
            {
                if (ViewState["data"] != null)
                {
                    DataTable dt = (DataTable)ViewState["data"];
                    DataView dv = new DataView(dt);
                    dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
                    ViewState["filter"] = dv;
                    gvEdit.DataSource = dv;
                    gvEdit.DataBind();
                    //gvformlist.DataSource = dv;
                    //gvformlist.DataBind();

                }

            }
        }
        catch (Exception ex)
        {
            string a = ex.Message;
        }

    }
    protected void Reset_Click(object sender, EventArgs e)
    {
        txtsearch.Text = "";
        gvEdit.DataSource = ViewState["data"];
        gvEdit.DataBind();
        //gvformlist.DataSource = ViewState["data"];
        //gvformlist.DataBind();

    }
    protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //gvEdit.PageIndex = e.NewPageIndex;
        //gvformlist.PageIndex = e.NewPageIndex;
        LoadFormList();

    }
    protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow pagerRow = gvEdit.TopPagerRow;
        Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
        }
    }
    protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvEdit.PageIndex = e.NewPageIndex;
        LoadFormList();

    }
    public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
    {
        // to Get No of pages and Page Navigation
        int pageIndex = gridView.PageIndex;
        int pageCount = gridView.PageCount;
        ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
        ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
        ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
        ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
        btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
        btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
        DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
        ddlPageSelector.Items.Clear();
        for (int i = 1; i <= gridView.PageCount; i++)
        {
            ddlPageSelector.Items.Add(i.ToString());
        }
        ddlPageSelector.SelectedIndex = pageIndex;
        string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
                            + gridView.PageCount.ToString();

        Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
        lblpageindx.Text += strPgeIndx;
    }
    protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
        LoadFormList();
    }

    protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
        }
    }
    protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
    {


    }

我已根据某人的建议代码更改 gvEdit_PageIndexChanging 中的代码

protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            if (ViewState["filter"] != null)
            {
                gvEdit.PageIndex = e.NewPageIndex;
                gvEdit.DataSource = ViewState["filter"];
                gvEdit.DataBind();
            }
            else
            {
                gvEdit.PageIndex = e.NewPageIndex;
                LoadFormList();
            }
        }
        catch (Exception ex)
        {
            string a = ex.Message;
        }


    }

之后我运行代码,我收到错误 错误是 System.Runtime.Serialization.SerializationException:在程序集'System.Data中输入'System.Data.DataView',Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'未标记为可序列化。

2 个答案:

答案 0 :(得分:1)

根据你的问题,我试着给出答案。如果您发现我的答案有用,则标记为答案或投票。

我在下面的代码中所做的是,当用户点击搜索按钮而没有输入任何学生姓名时,每页显示所有学生的10条记录,如果按名称搜索,则仅显示具有分页的特定学生。在下面的代码中,我使用了一个存储过程,并在其中放入了三个参数,如下所示:

@startRowIndex int 
@pageSize int
@studentname varchar(50) = NULL

Default.aspx 标记:

<form id="form1" runat="server">
    <asp:ScriptManager runat="server"></asp:ScriptManager>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <table>
                <tr>
                    <td>Gridview Pagging</td>
                </tr>
                <tr>
                    <td>
                        <asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        <asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
                    </td>
                </tr>
            </table>

            <div>
                <asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
                    ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
                    <Columns>
                        <asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
                        <asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
                    </Columns>
                    <EmptyDataRowStyle CssClass="emptyrow" />
                    <HeaderStyle CssClass="headerstyle2" />
                    <FooterStyle CssClass="footerstyle"></FooterStyle>
                    <EditRowStyle CssClass="editrowstyle"></EditRowStyle>
                    <SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
                </asp:GridView>
            </div>
            <div style="margin-top: 20px; margin-bottom: 70px;" align="center">
                <asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
                    Visible="False" />
                <asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
                    OnCommand="ChangePage" Visible="False" />
                <asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
                    Visible="False" />
                <asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
                    Visible="False" />
                <br />
                <br />
                <asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
                    BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
                <asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
                    BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
                <asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
                    BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
                <asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
                    BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

Default.aspx.cs 代码:

#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion

#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        ViewState["startRowIndex"] = 0;
        ViewState["currentPageNumber"] = 0;
    }
}
protected void ChangePage(object sender, CommandEventArgs e)
{
    switch (e.CommandName)
    {

        case "First":
            ViewState["currentPageNumber"] = 1;
            ViewState["startRowIndex"] = 0;

            break;
        case "Previous":
            ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
            ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;

            break;
        case "Next":
            ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
            ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;

            break;
        case "Last":
            ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
            ViewState["currentPageNumber"] = lbltotalPages.Text;
            break;
    }

    this.fillgridview();

}
protected void btnSearch_Click(object sender, EventArgs e)
{
    fillgridview();
}

#endregion

#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
    DataSet dataset;
    try
    {
        con = new SqlConnection(conquery);
        SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
        cmd.Parameters.AddWithValue("@startRowIndex", RowIndex);
        cmd.Parameters.AddWithValue("@pageSize", Pagesize);
        cmd.Parameters.AddWithValue("@studentname", studentname);
        cmd.CommandType = CommandType.StoredProcedure;
        using (SqlDataAdapter da = new SqlDataAdapter())
        {
            da.SelectCommand = cmd;
            dataset = new DataSet();
            da.Fill(dataset);
        }
        return dataset;
    }
    catch (SqlException ex)
    {
        return dataset = null;
    }
}
private void fillgridview()
{
    DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
    if (newds.Tables.Count == 0)
    {
        return;
    }
    else
    {
        btnFirst.Visible = true;
        btnPrevious.Visible = true;
        btnNext.Visible = true;
        btnLast.Visible = true;
        lblCurrentPage.Visible = true;
        lbltotalPages.Visible = true;
        lblPageText1.Visible = true;
        lblPageText2.Visible = true;

        ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
        newds.Tables[1].Rows.Clear();

        if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
        {
            ViewState["currentPageNumber"] = 1;
        }
        setPages();

        this.gv.Visible = true;
        this.gv.DataSource = newds.Tables[0];
        this.gv.DataBind();
    }
}
private void setPages()
{
    lbltotalPages.Text = "";
    lblCurrentPage.Text = "";
    try
    {
        lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
        lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());

        if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
        {
            this.btnPrevious.Enabled = false;
            this.btnFirst.Enabled = false;
            this.btnNext.Enabled = false;
            this.btnLast.Enabled = false;
        }
        else
        {
            if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
            {
                this.btnPrevious.Enabled = false;
                this.btnFirst.Enabled = false;

                if (int.Parse(lbltotalPages.Text) > 0)
                {
                    this.btnNext.Enabled = true;
                    this.btnLast.Enabled = true;
                }
                else
                {
                    this.btnNext.Enabled = false;
                    this.btnLast.Enabled = false;
                }
            }
            else
            {
                btnPrevious.Enabled = true;
                btnFirst.Enabled = true;

            }

            if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
            {
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
                btnLast.Enabled = true;
            }
        }
    }
    catch (Exception ex)
    {

    }
}
private int CalculateTotalPages(double totalrows)
{
    return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion

答案 1 :(得分:0)

首先在gridview中设置enablepagingandcallback = false,然后添加

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
    GridView1.DataBind();

}