3

I have a Editable GridView that I'm attempting to add sorting functionalty to specified columns. Though I receive no errors, My sorting method does not work. Could I please get some help on what I'm missing here?

The Design:

<asp:GridView ID="gvLogNotice" 
        runat="server" 
        AutoGenerateColumns="false" 
        ShowFooter="false"
        OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
        OnRowEditing="gvLogNotice_RowEditing" 
        OnRowUpdating="gvLogNotice_RowUpdating"
        EmptyDataText="There are no data records to display."
        DataKeyNames="LogNoticeID"
        AllowPaging="true"
        AllowSorting="true"
        OnSorting="gvLogNotice_sorting"
        Width="700px">
        <Columns>
            <asp:TemplateField HeaderText="Log No." Visible="false">
                <ItemTemplate>
                    <%#Eval("LogNoticeID")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
                </EditItemTemplate>
             </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
                <ItemTemplate>
                    <%#Eval("DateLogged")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
                <ItemTemplate>
                    <%#Eval("LogNoticeDescript")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
                </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
                <ItemTemplate>
                    <%#Eval("ResponsibleParty")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
                </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
                <ItemTemplate>
                    <%#Eval("PlannedDate")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
           <asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
                <ItemTemplate>
                    <%#Eval("CaseNumber")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
                <ItemTemplate>
                    <%#Eval("LogStatus")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
                </EditItemTemplate>
          </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    &nbsp;&nbsp;
                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
                        Height="25" CommandName="Edit" />&nbsp;&nbsp;
                   <%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
                        OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>&nbsp;&nbsp;
                    <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                </EditItemTemplate>
              </asp:TemplateField>
        </Columns>
    </asp:GridView>

Code behind:

//Page Load Event:

 protected void Page_Load(object sender, EventArgs e)
    {
        lblmsg.Text = "";
        if (!Page.IsPostBack)
        {
            gvLogNotice.ShowFooter = false;
            //Load grid data using common method
            LoadGrid();


        }
    }

//bind data to GV and Load

void LoadGrid()
        {
            sqlcmd = new SqlCommand("selectActiveLogs", sqlcon);
            sqlcmd.CommandType = CommandType.StoredProcedure;
            try
            {
                sqlcon.Open();
                da = new SqlDataAdapter(sqlcmd);
                dt.Clear();
                da.Fill(dt);
                gvLogNotice.DataSource = dt;
                gvLogNotice.DataBind();


            }
            catch (Exception ex)
            {

            }
            finally
            {
                sqlcon.Close();
            }
        }

//sorting event

  protected void gvLogNotice_sorting(object sender, GridViewSortEventArgs e)
    {
        switch (e.SortExpression)
        {
            case "DateLogged":
                if (e.SortDirection == SortDirection.Ascending)
                {
                   LoadGrid();
                }
                else
                {
                    LoadGrid();
                }

                break;

           }

    }
2
  • 1
    Does your code on those lines literally start with gvLogNotice.DataSource = // or did you leave something out there? Because that is the key part. Commented Sep 13, 2013 at 21:54
  • 1
    This page suggests that you need to set dt.DefaultView.Sort at some point to actually sort the grid, but I don't see it anywhere in your code... Commented Sep 14, 2013 at 15:44

1 Answer 1

2

The SortDirection property on the GridView is changed only when the GridView is bound to a DataSource control using the DataSourceID property. Otherwise, sort direction needs to be managed manually.

In this case when we provide Data to gridView using its DataSource property , e.SortDirection will always return Ascending. And therefore only your IF statement will always get executed.

Second Point:: You need to optimize actually is just make sure you define a function to return the Data only. e.g say LoadGrid() only returns the DataTable. This way you don't need to define overloads of your LoadGrid() method. Morover, with a proper way of implementation, overloading is really not needed at all.

Third point:: is that you aren't applying sorting at all, but just loading the GridView.When you databind manually by setting the DataSource property and calling DataBind(), you need to handle the sort operation manually.

So, start by storing your sortDirection in ViewState. Simply define a public property to Get/Set the same. [ NOTE we need to store the sortDirection value according to point 1 above ]

public SortDirection SortDirection    
{ 
get { 
      if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Ascending;
            }
        return (SortDirection)ViewState["SortDirection"];
     }
set
    {
           ViewState["SortDirection"] = value;
    }
}

In your OnSorting event, Set the sortDirection as well as firstly sort the table and then load it into gridView.

 protected void SortRecords(object sender, GridViewSortEventArgs e)
{
     string sortExpression = e.SortExpression;
     string direction = string.Empty;
        if (SortDirection == SortDirection.Ascending)
             {
                  SortDirection = SortDirection.Descending;
                  direction = " DESC";
             }
        else
            {
                 SortDirection = SortDirection.Ascending;
                 direction = " ASC";
            }
    DataTable table = this.LoadGrid(); // or this.GetDataTable(), to get only the DataTable
   // Now apply Sorting to your source of Data
    table.DefaultView.Sort = sortExpression + direction;
   // Bind the GridView
    gvLogNotice.DataSource = table;
    gvLogNotice.DataBind();
}

And last, your LoadGrid is fine, only thing that just fill the table and return it

private DataTable LoadGrid()
{
      DataTable dt = new DataTable();
      sqlcmd = new SqlCommand("selectActiveLogs", sqlcon);
      sqlcmd.CommandType = CommandType.StoredProcedure;
      try
       {
            sqlcon.Open();
            da = new SqlDataAdapter(sqlcmd);
            dt.Clear();
            da.Fill(dt);
            return dt;
       }
      catch (Exception ex)
       {}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.