locked
Newbie question - Gridview sort order lost on row edit + incorporate paging RRS feed

  • Question

  • User1862702016 posted

    Hi,

    Can someone point me in the right direction please? I've got gridview column sort order working correctly, but on row edit it loses the sort order and reverts to the initial ordering. I believe I need to capture the view state but being a newbie I'm struggling to do so!

     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    FillAllEnquiries();
    
                }
            }
    
            public void FillAllEnquiries()
            {
    
                DataTable dt = GetData("SELECT ...from ....");
                
                    Session["sort"] = dt.DefaultView.Sort;
                gvAllEnquiries.DataSource = dt;
                    gvAllEnquiries.DataBind();
    
            }
    
    
            private static DataTable GetData(string query)
            {
                string strConnString = ConfigurationManager.ConnectionStrings["centDB"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strConnString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
    
                        cmd.CommandText = query;
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataSet ds = new DataSet())
    
                            {
                                DataTable dt = new DataTable();
                                sda.Fill(dt);
    
                                return dt;
                            }
                        }
                    }
                }
            }
    
    
            protected void gvAllEnquiries_RowEditing(object sender, GridViewEditEventArgs e)
            {
                gvAllEnquiries.EditIndex = e.NewEditIndex;
                FillAllEnquiries();
            }
    
    
      private const string ASCENDING = " ASC";
            private const string DESCENDING = " DESC";
    
            public SortDirection GridViewSortDirection
            {
                get
                {
                    if (ViewState["sortDirection"] == null)
                        ViewState["sortDirection"] = SortDirection.Ascending;
    
                    return (SortDirection)ViewState["sortDirection"];
                }
                set { ViewState["sortDirection"] = value; }
            }
    
            protected void gvAllEnquiries_Sorting(object sender, GridViewSortEventArgs e)
            {
                
                    string sortExpression = e.SortExpression;
                     if (GridViewSortDirection == SortDirection.Ascending)
                    {
                        GridViewSortDirection = SortDirection.Descending;
                        SortGridView(sortExpression, DESCENDING);
                    }
                    else
                    {
                        GridViewSortDirection = SortDirection.Ascending;
                        SortGridView(sortExpression, ASCENDING);
                    }
    
            }
            private void SortGridView(string sortExpression, string direction)
            {
    
                DataTable dt = GetData("SELECT ...from ....");
         
                DataView dv = new DataView(dt);
                dv.Sort = sortExpression + direction;
                Session["sort"] = dv.Sort;
                gvAllEnquiries.DataSource = dv;
                gvAllEnquiries.DataBind();
            }

    Once this is rectified I'll then need to incorporate paging...so help with that would also be very much appreciated.

    Many thanks,

    Dom

    Tuesday, December 12, 2017 12:27 PM

Answers

  • User-707554951 posted

    Hi dh123xyz, 

    I notice that everytime when you click the Edit button, you'll have to edit the specific row and re-databind

    the datatable to the GridView again. However, you'll retieve the data from SQL db again with the original sort (select * from xxx).

    My solution is :

    1) you should bind ViewState as DataTable to the GridView and directly call GridView.DataBind()

    instead of calling gridbind() function.

    2) Use if to tell whether you ViewState is null or not, and re-fill data in that viewstate.

    Working code as below:

      <asp:GridView ID="gvAllEnquiries" runat="server" 
                OnRowEditing="gvAllEnquiries_RowEditing" AutoGenerateEditButton="true"   
                OnSorting="gvAllEnquiries_Sorting" AllowSorting="true" OnRowCancelingEdit="gvAllEnquiries_RowCancelingEdit" 
                AutoGenerateColumns="false"  AllowPaging="true" PageSize="3"  OnPageIndexChanging="gvAllEnquiries_PageIndexChanging">
                <Columns>
                    <asp:BoundField  DataField="SellId" SortExpression="SellId" HeaderText="SellId"/>
                     <asp:BoundField  DataField="UserName" SortExpression="UserName" HeaderText="UserName"/>
                </Columns>
                  <PagerSettings FirstPageText="First" LastPageText="End"   
                    NextPageText="&gt;z" />  
                <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
            </asp:GridView>

    CodeBehind:

    using System.Data;
    using System.Data.SqlClient;
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    FillAllEnquiries();
    
                }
            }
            public void FillAllEnquiries()
            {
                DataTable dt = GetData("SELECT * from Sells");
                Session["sort"] = dt.DefaultView.Sort;
                gvAllEnquiries.DataSource = dt;
                gvAllEnquiries.DataBind();
            }
            private static DataTable GetData(string query)
            {
                string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strConnString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = query;
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataSet ds = new DataSet())
                            {
                                DataTable dt = new DataTable();
                                sda.Fill(dt);
                                return dt;
                            }
                        }
                    }
                }
            }
    
            protected void gvAllEnquiries_RowEditing(object sender, GridViewEditEventArgs e)
            {
                gvAllEnquiries.EditIndex = e.NewEditIndex;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }         
            }  
    
        private const string ASCENDING = " ASC";
        private const string DESCENDING = " DESC";
        public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                {
                    ViewState["sortDirection"] = SortDirection.Ascending;
                }
    
                return (SortDirection)ViewState["sortDirection"];
            }
            set
            {
                ViewState["sortDirection"] = value;
    
            }
        }
    
        protected void gvAllEnquiries_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
                ViewState["dt"] = ((DataView)gvAllEnquiries.DataSource).ToTable();
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
                ViewState["dt"] = ((DataView)gvAllEnquiries.DataSource).ToTable();
            }
    
        }
        private void SortGridView(string sortExpression, string direction)
        {
            DataTable dt = GetData("SELECT * from Sells");
            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;
            Session["sort"] = dv.Sort;
            gvAllEnquiries.DataSource = dv;
            gvAllEnquiries.DataBind();
        }
        protected void gvAllEnquiries_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvAllEnquiries.EditIndex = -1;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }
            }
    
            protected void gvAllEnquiries_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                gvAllEnquiries.PageIndex = e.NewPageIndex;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }
            }
    

    Output:

    Best regards 

    Cathy 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 13, 2017 7:10 AM

All replies

  • User-707554951 posted

    Hi dh123xyz, 

    I notice that everytime when you click the Edit button, you'll have to edit the specific row and re-databind

    the datatable to the GridView again. However, you'll retieve the data from SQL db again with the original sort (select * from xxx).

    My solution is :

    1) you should bind ViewState as DataTable to the GridView and directly call GridView.DataBind()

    instead of calling gridbind() function.

    2) Use if to tell whether you ViewState is null or not, and re-fill data in that viewstate.

    Working code as below:

      <asp:GridView ID="gvAllEnquiries" runat="server" 
                OnRowEditing="gvAllEnquiries_RowEditing" AutoGenerateEditButton="true"   
                OnSorting="gvAllEnquiries_Sorting" AllowSorting="true" OnRowCancelingEdit="gvAllEnquiries_RowCancelingEdit" 
                AutoGenerateColumns="false"  AllowPaging="true" PageSize="3"  OnPageIndexChanging="gvAllEnquiries_PageIndexChanging">
                <Columns>
                    <asp:BoundField  DataField="SellId" SortExpression="SellId" HeaderText="SellId"/>
                     <asp:BoundField  DataField="UserName" SortExpression="UserName" HeaderText="UserName"/>
                </Columns>
                  <PagerSettings FirstPageText="First" LastPageText="End"   
                    NextPageText="&gt;z" />  
                <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
            </asp:GridView>

    CodeBehind:

    using System.Data;
    using System.Data.SqlClient;
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    FillAllEnquiries();
    
                }
            }
            public void FillAllEnquiries()
            {
                DataTable dt = GetData("SELECT * from Sells");
                Session["sort"] = dt.DefaultView.Sort;
                gvAllEnquiries.DataSource = dt;
                gvAllEnquiries.DataBind();
            }
            private static DataTable GetData(string query)
            {
                string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strConnString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = query;
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataSet ds = new DataSet())
                            {
                                DataTable dt = new DataTable();
                                sda.Fill(dt);
                                return dt;
                            }
                        }
                    }
                }
            }
    
            protected void gvAllEnquiries_RowEditing(object sender, GridViewEditEventArgs e)
            {
                gvAllEnquiries.EditIndex = e.NewEditIndex;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }         
            }  
    
        private const string ASCENDING = " ASC";
        private const string DESCENDING = " DESC";
        public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                {
                    ViewState["sortDirection"] = SortDirection.Ascending;
                }
    
                return (SortDirection)ViewState["sortDirection"];
            }
            set
            {
                ViewState["sortDirection"] = value;
    
            }
        }
    
        protected void gvAllEnquiries_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
                ViewState["dt"] = ((DataView)gvAllEnquiries.DataSource).ToTable();
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
                ViewState["dt"] = ((DataView)gvAllEnquiries.DataSource).ToTable();
            }
    
        }
        private void SortGridView(string sortExpression, string direction)
        {
            DataTable dt = GetData("SELECT * from Sells");
            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;
            Session["sort"] = dv.Sort;
            gvAllEnquiries.DataSource = dv;
            gvAllEnquiries.DataBind();
        }
        protected void gvAllEnquiries_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvAllEnquiries.EditIndex = -1;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }
            }
    
            protected void gvAllEnquiries_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                gvAllEnquiries.PageIndex = e.NewPageIndex;
                if (ViewState["dt"] != null)
                {
                    gvAllEnquiries.DataSource = (DataTable)ViewState["dt"];
                    gvAllEnquiries.DataBind();
                }
                else {
                    FillAllEnquiries();
                }
            }
    

    Output:

    Best regards 

    Cathy 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 13, 2017 7:10 AM
  • User1862702016 posted

    ...post deleted and started a new thread

    Thursday, December 14, 2017 11:16 AM