简体   繁体   中英

GridView lost search result after change page size or click on paging?

I have a gridview to show the data and and text box to do the search. When i search, the gridview could show the data correctly, but when I click on change page size or go to next page, the gridview will reload to the original state. Is there anything to do with the ViewState? Appreciate is someone could help. following is my code:

protected void Page_Load(object sender, EventArgs e)
        {


        }

    protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        // handle event                 
        DropDownList ddpagesize = sender as DropDownList;
        GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
        ViewState["PageSize"] = ddpagesize.SelectedItem.Text;             
        GridView1.DataBind();

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";                   
        GridView1.DataBind();            

    }

    protected void btnReload_Click(object sender, EventArgs e)
    {

        txtSearchValue.Text = "";
        lblSearchError.Text = "";
        GridView1.DataBind();

    }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                row.Attributes["onmouseover"] =
                   "this.style.backgroundColor;this.style.backgroundColor='#AED4EB';";
                row.Attributes["onmouseout"] =
                   "this.style.textDecoration='none';this.style.background='#ffffff';";
                // Set the last parameter to True 
                // to register for event validation. 
                row.Attributes["onclick"] =
                 Page.ClientScript.GetPostBackClientHyperlink(GridView1,
                    "Select$" + row.DataItemIndex, true);
            }
        }
        base.Render(writer);
    }

    protected void btnDate_Click(object sender, EventArgs e)
    {

        SqlDataSource1.SelectCommand = "";
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            int rowindex = GridView1.SelectedIndex % GridView1.PageSize;
            GridViewRow row = GridView1.Rows[rowindex];
            Session["TSO"] = row.Cells[7].Text.Trim();
            string url = "http://localhost:60918/Requests.aspx";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script type='text/javascript'>");
            sb.AppendLine("window.open('" + url + "')");
            sb.AppendLine("<" + "/script>");
            ScriptManager.RegisterStartupScript(upGrdCustomers, upGrdCustomers.GetType(), "myjs", sb.ToString(), false);
        }
        catch (System.Threading.ThreadAbortException)
        {
            throw;
        }                  

    }

Here is my code for the GridView:

[ToolboxData("<{0}:GridView runat=server></{0}:GridView>")]

public class GridView : System.Web.UI.WebControls.GridView, IPageableItemContainer
{
    /// <summary>
    /// TotalRowCountAvailable event key
    /// </summary>
    private static readonly object EventTotalRowCountAvailable = new object();

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dataSource"></param>
    /// <param name="dataBinding"></param>
    /// <returns></returns>
    protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
    {
        int rows = base.CreateChildControls(dataSource, dataBinding);

        //  if the paging feature is enabled, determine
        //  the total number of rows in the datasource
        if (this.AllowPaging)
        {
            //  if we are databinding, use the number of rows that were created,
            //  otherwise cast the datasource to an Collection and use that as the count
            int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;

            //  raise the row count available event
            IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;
            this.OnTotalRowCountAvailable(
                new PageEventArgs(
                    pageableItemContainer.StartRowIndex,
                    pageableItemContainer.MaximumRows,
                    totalRowCount
                )
            );

            //  make sure the top and bottom pager rows are not visible
            if (this.TopPagerRow != null)
            {
                this.TopPagerRow.Visible = false;
            }


        }

        return rows;
    }

    #region IPageableItemContainer Interface

    /// <summary>
    /// 
    /// </summary>
    /// <param name="startRowIndex"></param>
    /// <param name="maximumRows"></param>
    /// <param name="databind"></param>
    void IPageableItemContainer.SetPageProperties(
        int startRowIndex, int maximumRows, bool databind)
    {
        int newPageIndex = (startRowIndex / maximumRows);
        this.PageSize = maximumRows;

        if (this.PageIndex != newPageIndex)
        {
            bool isCanceled = false;
            if (databind)
            {
                //  create the event args and raise the event
                GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);
                this.OnPageIndexChanging(args);

                isCanceled = args.Cancel;
                newPageIndex = args.NewPageIndex;
            }

            //  if the event wasn't cancelled
            //  go ahead and change the paging values
            if (!isCanceled)
            {
                this.PageIndex = newPageIndex;

                if (databind)
                {
                    this.OnPageIndexChanged(EventArgs.Empty);
                }
            }

            if (databind)
            {
                this.RequiresDataBinding = true;
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    int IPageableItemContainer.StartRowIndex
    {
        get { return this.PageSize * this.PageIndex; }
    }

    /// <summary>
    /// 
    /// </summary>
    int IPageableItemContainer.MaximumRows
    {
        get { return this.PageSize; }
    }

    /// <summary>
    /// 
    /// </summary>
    event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable
    {
        add { base.Events.AddHandler(GridView.EventTotalRowCountAvailable, value); }
        remove { base.Events.RemoveHandler(GridView.EventTotalRowCountAvailable, value); }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="e"></param>
    protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
    {
        EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[GridView.EventTotalRowCountAvailable];
        if (handler != null)
        {
            handler(this, e);
        }
    }

    #endregion

}

}

In your server side event handler called ddPageSize_SelectedIndexChanged you are calling Databind on your grid without checking if there is a search term entered and setting that on the DataSource of the Grid.

protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)

{ ...

SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";

GridView1.DataBind();

}

Try this. When you change the pagesize it triggers a postback and leaving the value for SelectCommand as empty resulting the gridview to load in it's original state. Set it to txtSearchValue.Text and try

protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
    // handle event                 
    DropDownList ddpagesize = sender as DropDownList;
    GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
    ViewState["PageSize"] = ddpagesize.SelectedItem.Text;    
    SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";          
    GridView1.DataBind();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM