In this article, we will learn how to implement the sorting and pagination of the data being in GridView. You can sort the data in ascending as well as in the descending order by clicking on the columns name of the GridView.

How to sort data in ASP.NET GridView using column headers

GridView is a powerful data grid control which allows us to display the values of a data source in a table format where each column represents a field and each row represents a record. The GridView control lets you select, sort, or edit these data values.

Each column in the GridView control is represented by an instance of DataControlField. The column field can have different types that determine the behavior of the columns in the control.

To create a sortable column, you need to use the TemplateField column filed type. This allows displaying user-defined content for each item. You can also create a custom column field according to the column field type.

Let’s create a simple page to understand the sorting process.

HTML

Start by adding a GridView to your web page. To make the columns sortable, you need to set the GridView’s property AllowSorting = “true” and OnSorting = “OnSorting”. SortExpression property will hold the name of the column you want to sort.

    <div>
        <asp:GridView ID="gvCustomers" OnSorting="OnSorting" runat="server" AutoGenerateColumns="false" CssClass="gv"
            AllowSorting="True" CellPadding="4" DataKeyNames="CustomerId">
            <Columns>
                <asp:TemplateField
                    HeaderText="Customer ID"
                    SortExpression="CustomerId">

                    <ItemTemplate>
                        <%# Eval("CustomerId")%>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:BoundField DataField="CustomerName"
                    HeaderText="Customer Name"
                    SortExpression="CustomerName" />
                <asp:BoundField
                    DataField="CustomerEmail"
                    HeaderText="Cutomer Email"
                    SortExpression="CustomerEmail" />
                
            </Columns>
        </asp:GridView>
    </div>

CSS

    <style>
        .gv {
            border: solid 2px black;
        }

        .header {
            background-color: #646464;
            font-family: Arial;
            color: White;
            border: none 0px transparent;
            height: 25px;
            text-align: center;
            font-size: 16px;
        }

        .rows {
            background-color: #fff;
            font-family: Arial;
            font-size: 14px;
            color: #000;
            min-height: 25px;
            text-align: left;
            border: none 0px transparent;
        }

        .gv td {
            padding: 5px;
        }

        .gv th {
            padding: 5px;
        }
    </style>

OnSorting event fires OnSorting server-side function.

C#

The first step is to insert data to GridView using  the BindData method

private DataTable BindData(string sortExpression)
    {
        DataTable table = new DataTable();
        string conn_str = "Data Source=localhost;Initial Catalog=books;Integrated Security=True";
        using (SqlConnection conn = new SqlConnection(conn_str))
        {

            StringBuilder sql = new StringBuilder("SELECT * FROM customers");


            if (!string.IsNullOrEmpty(sortExpression))
            {
                this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
                sql.Append(" Order By " + sortExpression + " " + SortDirection);
            }

            using (SqlCommand cmd = new SqlCommand(sql.ToString(), conn))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(table);
                }
            }
        }
        return table;
    }
}

Then call this function from the Page_Load event

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvCustomers.DataSource = BindData("");
        gvCustomers.DataBind();

    }
}

The condition !isPostBack ensures that the data binding request is not a result of any postback request. SortDirection property holds the sorting direction which is either ASC or DESC.

protected void OnSorting(object sender, GridViewSortEventArgs e)
{
    gvCustomers.DataSource = BindData(e.SortExpression);
    gvCustomers.DataBind();
}

When the user clicks on the column name of the GridVeiw, the server-side method OnSorting is executed which further saves the sort expression (the name of the column) and sort direction.

As we are using the DataTable, we have to use the sort Expression which allows sorting the rows of the DataTable. After getting it sorted, the GridView data source has set and the DataBind method is called.

The value of the SortDirection is saved in a ViewState object. If the current value is ASC, then the next time the user clicks on the grid header, the sort order will be DESC and vise Versa.

private string SortDirection
{
    get
    {
        return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC";
    }
    set
    {
        ViewState["SortDirection"] = value;
    }
}

When a grid pagination link is clicked, the value of the PageIndex of the page changes and an event, a handler is executed.

The NewPageIndex is the property of the GridViewPageEventArgs object and it is set to the PageIndex property of the Gridview.

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvCustomers.PageIndex = e.NewPageIndex;
    BindData(SortDirection);

}

Related Articles

Last modified: October 13, 2019

Comments

Write a Reply or Comment

Your email address will not be published.