ASP.NET - sort datagridview - Asked By aman on 03-Aug-11 05:25 AM

hi all,

how to sort DataGridView in asp.net.

thanks
regards
Aman
Ravi S replied to aman on 03-Aug-11 05:34 AM
HI

Step I )


In the Datagrid definition:
add 2 properties AllowSorting = true and OnSortCommand=”MethodName in code behind”

e.g
<asp:datagrid id=”dgSearchList” runat=”server” Height=”125px” Width=”627px” CssClass=”panelChildSolidBorder”
CellPadding=”2″ AllowCustomPaging=”True” AutoGenerateColumns=”False” OnItemCommand=”detailsClicked”
ShowHeader=”True” AllowSorting=”True” OnSortCommand=”dgSearchList_SortClick” PageSize=”4″>

AllowSorting=”True”
makes the datagrid sortable and OnSortCommand=”dgSearchList_SortClick” tells which method to call when the header is clicked.


Step II )

Now we need to define the method to call when the column headers are clicked
here dgSearchList_SortClick is the method that will be called when the Column headers are clicked for sorting.

Codebehind :

public void dgSearchList_SortClick(object sender,DataGridSortCommandEventArgs e)
{
sortField = e.SortExpression; // ie the Sortexpression assigned to the Column.Check STEP III for how to assign a   // sortexpression on a column.
PopulateDatagrid(); //Call the method that populates the Datagrid with
//the values from the Dataview.
}

PopulateDatagrid()
{
if(sortMode.ToString().Trim().Equals(SORT_ASC))
{
sortMode = SORT_DESC; // Here sortMode is just a Variable storing the
direction of the sort.There are better ways to store this than the current one shown hereJ
}
else
{
sortMode = SORT_ASC;
}
txtSortMode.Text = sortMode;

// SORT_DESC and SORT_ASC are constants with the following string values.
// SORT_DESC = “Desc”
// SORT_ASC = “Asc”

DataView dv = new DataView(dt);
dv.Sort = sortField.Trim() + ” ” + sortMode;
dgSearchList.DataSource = dv;
dgSearchList.DataBind();

}

The code above checks whether we want to sort in Ascending order or in Descending order
and assigns the SortExpression concatenated with the Sorting direction (Asc/Desc)
and binds the datagrid again (don’t forget to bind the data grid its very important)

Step III)
You need to specify the sorting expression for that column in the column definition in the ASPX page

e.g
<asp:BoundColumn DataField=”Location” SortExpression=”Location” HeaderText=”LocationArea”>
<ItemStyle Height=”10px” Width=”10px”><!–ItemStyle>
asp:BoundColumn>

be carefull of what you define as the sortexpression because this is what is passed to the codebehind and sortexpression is what identifies which column was clicked for sorting

in this case the sort expression for the LocationArea column is “Location”, hence when we clicking on the location column will set the e.SortExpression (check Step III for e.SortExpression) to “Location”. Hence identifying the column clicked.

Jitendra Faye replied to aman on 03-Aug-11 05:34 AM
Assuming that you have placed a DataGrid on your ASP.NET page, I follow these steps.

1) Right-click the DataGrid and select the Property Builder menu option.  On the General Tab, check the Allow Sorting Checkbox.

2) On the Columns Tab, for each column that you want to sort, enter the query field name of that column in the Sort Expression box.  This is what turns on the underline on the respective grid column.  If a column header is not underlined in the designer, it will not be sortable.  The underline will only appear when you click the Apply button or the Ok button to exit the Property Builder.  By the way, this is the step that some books by well-know authors leave out and it can be baffling why the header text is not underlined.

3) Create a DataView object at the class level, such as the following.  Remember, in a Stateless environment, no variables are automatically saved, and therefore must be saved in Session Variables.  So, I save the contents of the DataView in a Session Variable thoughout it's usage.

  private DataView dv;

4) In the Page Load event, I will place some code that looks something like this.

  private void Page_Load(object sender, System.EventArgs e)
  {
    
// Put user code to initialize the page here
    if(!Page.IsPostBack)
    {
    ShowData();
    }
  }

5) The ShowData method is responsible for getting the data and calling the BindData method.

  private void ShowData()
  {
    
int authorID = Convert.ToInt32(Session["AuthorID"]);
    DateTime stDate = (DateTime)Session[
"StartDate"];
    DateTime endDate = (DateTime)Session[
"EndDate"];
    DataTable dt = blj.GetDictationByAuthorID(authorID, stDate, endDate);
    // set the dataview object to the datatable DefaultView
    dv = dt.DefaultView;
    Session[
"DictatedDV"] = dv;
    BindData("");
  }

6) Iwill call the BindData method to bind the dataview to the grid.

  private void BindData(string sortExpression)
  {
    
// reset the dataview, else it will be undefined value!
    dv=(DataView)Session[
"DictatedDV"];
    
if(sortExpression.Length>0)
    {
    dv.Sort=sortExpression;
    
// save the dataview in stateless environment
    Session["DictatedDV"] = dv;
    }
    
this.DataGrid1.DataSource=dv;
    
this.DataGrid1.DataBind();
  }

7) Switch back to the designer and click on the DataGrid and then show the Property window for the grid.  Click the events button(lighnning bolt) and double-click in the SortCommand event.  That will create a DataGrid1_SortCommand event.  Enter the code shown below into the event.  In this event, I set the SortExpression, which you will recall is the field name of the data column in the designer.  This is actually a string name of the column to sort on.

  private void DataGrid1_SortCommand(object source,
     System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
  {
    BindData(e.SortExpression);
  }

8) Now, we can sort, but only in one direction, ascending.  At this point our grid does not support sorting in both directions.  That can be solved by enhancing the code for the SortCommand event shown above.  I will simplly remember the last order that we sorted in and reverse that direction with the code shown below.

  private void DataGrid1_SortCommand(object source,
    System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
  {
    
string sortExpression = (string)Session["SortExp"];
    
string sortDirection = (string)Session["SortDir"];

    
if(sortExpression != e.SortExpression)
    {
    sortExpression = e.SortExpression;
    sortDirection =
"asc";
    }
    
else
    {
    
if(sortDirection == "asc")
      sortDirection =
"desc";
    
else
      sortDirection = "asc";
    }
    
    Session[
"SortExp"] = sortExpression;
    Session[
"SortDir"] = sortDirection;
    BindDataGrid(sortExpression +
" " + sortDirection);
  }
follow this link-

http://www.knowdotnet.com/articles/sortingaspgrid.html
Ravi S replied to aman on 03-Aug-11 05:34 AM
HI

try this

<asp:datagrid id="dgTest" Runat="server" Width="90%" 
          EnableViewState="False" ShowHeader="True"
          AutoGenerateColumns="False" GridLines="Horizontal" 
          BackColor="lightblue">
    <HeaderStyle Wrap="False" Font-Bold="True" BackColor="#3300cc" 
                          ForeColor="white"></HeaderStyle>
    <AlternatingItemStyle BackColor="LawnGreen"></AlternatingItemStyle>
    <Columns>
      <asp:BoundColumn HeaderText="Last Name" DataField="LastName" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="First Name" DataField="FirstName" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="Address" DataField="Address" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="City" DataField="city" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="Region" DataField="Region" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="PostalCode" DataField="PostalCode" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:BoundColumn HeaderText="Country" DataField="Country" 
                          ReadOnly="True"></asp:BoundColumn>
      <asp:TemplateColumn>
        <HeaderTemplate>
          View Detail
        </HeaderTemplate>
        <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
        <ItemTemplate>
          <asp:LinkButton ID="lnkSelect" Runat="server" 
                    text="Select"></asp:LinkButton>
        </ItemTemplate>
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
      </asp:TemplateColumn>
    </Columns>
</asp:datagrid>
<br>
<asp:Button ID="SortButton" style="DISPLAY:none" Runat="server" 
                                  Text="Sort"></asp:Button>


private void SortButton_Click(object sender, System.EventArgs e)
{
    SORT_ORDER order = (SORT_ORDER)ViewState[SORTORDER];
    
    if(order == SORT_ORDER.ASC)
    {
        this.BindData(SORT_ORDER.DESC);
    }
    else
    {
        this.BindData(SORT_ORDER.ASC);
    }
}

refer the link for full code

http://www.codeproject.com/KB/webforms/OptimizedDataGridSort.aspx
Mitesh Darji replied to aman on 03-Aug-11 05:39 AM
can you please check below link:

you can download sample sorting application(.zip) from below location:

http://www.daniweb.com/forums/attachment.php?attachmentid=13063&d=1261752350
Reena Jain replied to aman on 03-Aug-11 05:44 AM
Hi,

You just give which AllowSorting=true for that gridview. and for which datafiled u want to sort then give that filed property  Sortxpression="Columnname"

EX
<asp:GridView ID="gvCategories" runat="server" AllowSorting="True" OnSorting="gvCategories_Sorting">
<asp:BoundField DataField="D_NAME" HeaderText="Deptartment" SortExpression="D_NAME" />


Onsorting contain a method
 protected void gvCategories_Sorting(object sender, GridViewSortEventArgs e)
    {
      ViewState["sortExpr"] = e.SortExpression;
      gvCategories.DataSource = bindgrid();
      gvCategories.DataBind();
    }
Radhika roy replied to aman on 03-Aug-11 11:33 AM

Using Sort Property of DataView you can sort GridView.

You have to also implement GridView1_Sorting() event,.

Use this code-

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 GridView1_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)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0]; 

DataView dv = new DataView(dt); 
dv.Sort = sortExpression + direction; 

GridView1.DataSource = dv;
GridView1.DataBind(); 
}

Try this code and let me know.