Question

In my application I am sorting the gridview and also have Edit in that gridview, sorting works fine but when i click Edit, it puts the gridview in the original sorted order. when i click Edit - it lets me edit the row but it changes the order and show me the original record on that row in the edit mode.

private void LoadGridview()
    {
        DataTable dt = new DataTable();

        using (SqlConnection cs = new SqlConnection(connStr))
        {
            if (Session["sortedGV"] == null )
            {
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter("spManagement_GetStationProfile", cs);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.AddWithValue("@Que", ddlQue.SelectedValue);
                da.Fill(ds);
                dt = ds.Tables[0];

                Session["sortedGV"] = new DataView(dt);
            }
        }
        gvStations.DataSource = Session["sortedGV"];
        gvStations.DataBind();
    }

protected void gvStations_RowCommand(object sender, GridViewCommandEventArgs e)
{
            if (e.CommandName == "EditRow")
            {
                //This enables the EditTemplate
                int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
                gvStations.EditIndex = rowindex; //Enables the edit row in gridview                        
            }
            else if (e.CommandName == "CancelUpdate")
            {
                gvStations.EditIndex = -1;
            }
            else if (e.CommandName == "UpdateRow")
            {
                //DO SOME STUFF///
                gvStations.EditIndex = -1; //Takes you out of update view      
            }

            if ((DataTable)Session["sortedGV"] != null)
            {                    
                gvStations.DataSource = (DataTable)Session["sortedGV"];
            }
            else
            {
                gvStations.DataSource = LoadGridview();
            }
            gvStations.DataBind();
            btnAddStation.Visible = true;
  }
  private void SortGridview(string sortExpression, string Direction)
    {
        DataView dv = null;
        DataTable dt = gvStations.DataSource as DataTable;
        dv = new DataView(dt);

        dv.Sort = sortExpression + " " + Direction;
        Session["sortedGV"] = dt;
        gvStations.DataSource = dv;
        gvStations.DataBind();

    }

    //Sorts gridview
    protected void gvStations_Sorting(object sender, GridViewSortEventArgs e)
    {
        String sortExpression = e.SortExpression;
        Session["SortExpression"] = sortExpression;

        if (Session["SortDirection"] != null && Session["SortDirection"].ToString() == SortDirection.Descending.ToString())
        {
            Session["SortDirection"] = SortDirection.Ascending;
            SortGridview(sortExpression, "ASC");
        }
        else
        {
            Session["SortDirection"] = SortDirection.Descending;
            SortGridview(sortExpression, "DESC");
        }

    }

Gridview

<asp:GridView ID="gvStations" runat="server" AutoGenerateColumns="False" DataKeyNames="StationID"
            Width="100%" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None"
            OnRowCommand="gvStations_RowCommand" OnSorting="gvStations_Sorting">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField ShowHeader="False">
                    <ItemTemplate>
                        <asp:LinkButton ID="lbEdit" runat="server" CausesValidation="False" CommandName="EditRow"
                            CommandArgument='<%# Eval("StationId")%>'>Edit</asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lbUpdate" runat="server" CausesValidation="True" CommandName="UpdateRow"
                            ForeColor="White" Text="Update" CommandArgument='<%# Eval("StationId")%>'></asp:LinkButton>
                        <asp:LinkButton ID="lbCancel" runat="server" CausesValidation="False" CommandName="CancelUpdate"
                            ForeColor="White" CommandArgument='<%# Eval("StationId")%>' Text="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <FooterStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:BoundField DataField="StationID" HeaderText="ID" SortExpression="StationID"
                    Visible="false" ReadOnly="true">
                    <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <%--Station Number--%>
                <asp:TemplateField HeaderText="#" SortExpression="StationNumber">
                    <EditItemTemplate>
                        <asp:TextBox ID="tbStationNumberEdit" runat="server" Text='<%# Eval("StationNumber") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbStationNumber" runat="server" Text='<%# Eval("StationNumber") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
              </Columns>  
          </asp:GridView>
Was it helpful?

Solution

You need to save the DataView in the session and use it. Not the DataTable. The following modification makes the code work. Also note that the Sort command runs in the RowCommand method first and then invokes your Sorting method so it's best to data bind explicitly for each command in the RowCommand event method.

    private string SortExpression
    {
        get { return (string) Session["SortExpression"]; }
        set { Session["SortExpression"] = value; }
    }

    private string Direction
    {
        get { return (string)Session["SortDirection"]; }
        set { Session["SortDirection"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGridview();
        }
    }

    protected void gvStations_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditRow")
        {
            //This enables the EditTemplate
            int rowindex = ((GridViewRow) ((LinkButton) e.CommandSource).NamingContainer).RowIndex;
            gvStations.EditIndex = rowindex; //Enables the edit row in gridview      

            LoadGridview();
        }
        else if (e.CommandName == "CancelUpdate")
        {
            gvStations.EditIndex = -1;
            LoadGridview();
        }
        else if (e.CommandName == "UpdateRow")
        {
            var dataView = (DataView) Session["sortedGV"];


            //DO SOME STUFF///
            gvStations.EditIndex = -1; //Takes you out of update view     


            LoadGridview();
        }
    }

    private void LoadGridview()
    {
        if (Session["sortedGV"] == null)
        {
            var table = new DataTable();
            table.Columns.Add("StationId", typeof (int));
            table.Columns.Add("StationNumber", typeof (string));
            DataRow row1 = table.NewRow();
            row1["StationId"] = 1;
            row1["StationNumber"] = "343";
            table.Rows.Add(row1);

            DataRow row2 = table.NewRow();
            row2["StationId"] = 2;
            row2["StationNumber"] = "443";
            table.Rows.Add(row2);

            Session["sortedGV"] = new DataView(table);
            SortGrid();
        }


        gvStations.DataSource = Session["sortedGV"];
        gvStations.DataBind();
    }


    private void SortGrid()
    {
        var dv = (DataView) Session["sortedGV"];
        if (SortExpression != null)
        {
            dv.Sort = SortExpression + " " + Direction;

        }
    }


    //Sorts gridview
    protected void gvStations_Sorting(object sender, GridViewSortEventArgs e)
    {
        SortExpression = e.SortExpression;

        if (SortExpression != null &&
            Direction == SortDirection.Descending.ToString())
        {
            Direction = "ASC";
        }
        else
        {
            Direction = "DESC";       
        }
        SortGrid();
        LoadGridview();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top