Solved

Keeping track of values in datatable while paging gridview

Posted on 2008-06-16
5
978 Views
Last Modified: 2013-11-07
I have a page and when it loads, a gridview is populated with 1000 records. I have two text boxes which searches first name and last name.
Anytime i type in "be" for the lastname to search, I only see a page of data. If i click on page 2 i start seeing other data not related to "lastname = be" . I thought the value of "be" is not in view state and i put it in view state but still getting the same problem. Page 1 works well but other pages do not. Pls assist.
/// <summary>
    /// 
    /// </summary>
    private string GridViewSortDirection
    {
        get { return ViewState["SortDirection"] as string ?? "ASC"; }
        set { ViewState["SortDirection"] = value; }
    }
 
 
    /// <summary>
    /// 
    /// </summary>
    private string GridViewSortExpression
    {
        get { return ViewState["SortExpression"] as string ?? string.Empty; }
        set { ViewState["SortExpression"] = value; }
    }
 
 
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private string GetSortDirection()
    {
        try
        {
            switch (GridViewSortDirection)
            {
                case "ASC":
                    GridViewSortDirection = "DESC";
                    break;
                case "DESC":
                    GridViewSortDirection = "ASC";
                    break;
            }      
        }        
        catch(Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
        return GridViewSortDirection;
    }
 
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void sdgridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            sdgridview.DataSource = SortDataTable(sdgridview.DataSource as DataTable, true);
            sdgridview.PageIndex = e.NewPageIndex;
            //dots
            sdgridview.DataBind();
            
        }
        catch (Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
    }
        
    /// <summary>
    /// 
    /// </summary>
    /// <param name="dataTable"></param>
    /// <param name="isPageIndexChanging"></param>
    /// <returns></returns>
    protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
    {
        try
        {
            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                if (GridViewSortExpression != string.Empty)
                {
                    if (isPageIndexChanging)
                    {
                        dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection);
                    }
                    else
                    {
                        dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection());
                    }
                }
                return dataView;
            }
            //else
            //{
                //return new DataView();
            //}
        }
        catch (Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
        return new DataView();
    }
 
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void sdgridview_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            GridViewSortExpression = e.SortExpression;
            int pageIndex = sdgridview.PageIndex;
            sdgridview.DataSource = SortDataTable(sdgridview.DataSource as DataTable, false);
            //dots here
            sdgridview.DataBind();
            sdgridview.PageIndex = pageIndex;
        }
        catch (Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
    }
 
 
 
protected void btnsearch_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtfirstname.Text == "" & txtlastname.Text == "")
            {
                lblresult.Visible = true;
                lblresult.Text = "You Cannot search for blank values. Enter a value for last name or first name";
                sdgridview.Visible = false;
            }
            else
            {
                lblresult.Visible = false;
                sdgridview.Visible = true;
                PopulateGridByCriteria();
            }
        }
        catch (Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
    }
 
 
private void PopulateGridByCriteria()
    {
        try
        {
            string connectionString = AccessConnectionString();
            cn = new SqlConnection(connectionString);
            da = new SqlDataAdapter("DisplaystudentByCriteria", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add(new SqlParameter("@surname",SqlDbType.VarChar,30));
            //da.SelectCommand.Parameters["@surname"].Value = txtlastname.Text;
            CurrentLastNameSearch = txtlastname.Text;
            da.SelectCommand.Parameters["@surname"].Value = CurrentLastNameSearch;
 
            da.SelectCommand.Parameters.Add(new SqlParameter("@Firstname", SqlDbType.VarChar, 30));
            da.SelectCommand.Parameters["@Firstname"].Value = txtfirstname.Text;
            studDT = new DataTable();
            da.Fill(studDT);
            int dataTableRowCountByCriteria = studDT.Rows.Count;
            if (dataTableRowCountByCriteria > 0)
            {
                sdgridview.Visible = true;
                //lblresult.Visible = false;
                sdgridview.DataSource = studDT;
                sdgridview.DataBind();
                sdgridview.Columns[0].Visible = false;
            }
            else
            {
                lblresult.Visible = true;
                sdgridview.Visible = false;
                lblresult.Text = "No record found";
            }
        }
        catch(Exception ex)
        {
            Response.Redirect("Error.aspx"); 
        }
    }
 
 
 
public string CurrentLastNameSearch
    {
        get
        {
            return (string)ViewState["Current"];
        }
        set
        {
            ViewState["Current"] = value;
        }
 
    }

Open in new window

0
Comment
Question by:Sirdots
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 5

Expert Comment

by:scgstuff
ID: 21797460
Try:

protected void sdgridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            PopulateGridByCriteria();
            sdgridview.PageIndex = e.NewPageIndex;
            //dots
            sdgridview.DataBind();
           
        }
        catch (Exception ex)
        {
            Response.Redirect("Error.aspx");
        }
    }
0
 

Author Comment

by:Sirdots
ID: 21797608
Thanks for your assistance scqstuff. Your code works but has broken my initial data that i load on page load. Presently, once my page loads, it is only the first page that is sorted in ascending order. once i click on the second page, no more ascending order. I will start seeing last name starting with V

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //if (!this.IsPostBack)
            //{
            //    PopulateStudentDirecGrid();
            //}
           
                PopulateStudentDirecGrid();

        }
        catch(Exception ex)
        {
            Response.Redirect("Error.aspx");
        }            
    }



 private void PopulateStudentDirecGrid()
    {
        try
        {
                             
            //DataSet ds = new DataSet();
            string connectionString = AccessConnectionString();
            sdcmd = new SqlCommand();
            sdcmd.CommandText = "DisplayAllStudentDirectory";
            cn = new SqlConnection(connectionString);
            cn.Open();
            sdcmd.Connection = cn;
            sdcmd.CommandType = CommandType.StoredProcedure;
            da = new SqlDataAdapter(sdcmd);

            DataTable studentDT = new DataTable("StudentD");
            da.Fill(studentDT);
            int dataTableRowCount = studentDT.Rows.Count;

            if (dataTableRowCount > 0)
            {
                sdgridview.Visible = true;
                lblresult.Visible = false;
                sdgridview.DataSource = studentDT;
                sdgridview.DataBind();
                sdgridview.Columns[0].Visible = false;
            }                  
        }
        catch(Exception ex)
        {
            //Session["Exception"] = ex;
            Response.Redirect("Error.aspx");        
        }

    }
0
 
LVL 5

Expert Comment

by:scgstuff
ID: 21797810
You may want to join the PopulateStudentDataGrid and PopulateGridByCriteria into one sub and then do an if txtLastname not null then commandtext = DisplayStudentByCriteria else DisplayAllStudentDirectory.  I think that would allow you to add the data needed to the grid and select an index page before databinding.  

Shawn
0
 

Author Comment

by:Sirdots
ID: 21798718
Thanks for your comment. The reason why i seperated them is that I have a button link on the page which calls the PopulateStudentGrid which displays all record and not specific record. do you know how I can incorporate this within the same method?

0
 
LVL 5

Accepted Solution

by:
scgstuff earned 500 total points
ID: 21798886
I don't have the test page setup, but I have tried to put the code togther the way I think it would read.  Try this:

    private void PopulateStudentDirecGrid()
    {
        try
        {
            string connectionString = AccessConnectionString();
            sdcmd = new SqlCommand();
            cn = new SqlConnection(connectionString);
            cn.Open();
            sdcmd.Connection = cn;
            sdcmd.CommandType = CommandType.StoredProcedure;
            if (txtlastname.Text = "" && txtfirstname.Text)
            {
                sdcmd.CommandText = "DisplayAllStudentDirectory";
                da = new SqlDataAdapter(sdcmd);
            }
            else
            {
                da = new SqlDataAdapter("DisplaystudentByCriteria", cn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.Add(new SqlParameter("@surname",SqlDbType.VarChar,30));
                CurrentLastNameSearch = txtlastname.Text;
                da.SelectCommand.Parameters["@surname"].Value = CurrentLastNameSearch;
                da.SelectCommand.Parameters.Add(new SqlParameter("@Firstname", SqlDbType.VarChar, 30));
                da.SelectCommand.Parameters["@Firstname"].Value = txtfirstname.Text;
            }
            DataTable studentDT = new DataTable("StudentD");
            da.Fill(studentDT);
            int dataTableRowCount = studentDT.Rows.Count;

            if (dataTableRowCount > 0)
            {
                sdgridview.Visible = true;
                lblresult.Visible = false;
                sdgridview.DataSource = studentDT;
                sdgridview.DataBind();
                sdgridview.Columns[0].Visible = false;
            }
        }
        catch (Exception ex)
        {
            //Session["Exception"] = ex;
            Response.Redirect("Error.aspx");
        }
    }
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question