Gridview Sorting Paging with Default Asc Desc Arrow using C# and VB.Net in ASP.Net

Babloo18v
 
on Jun 02, 2017 03:37 AM
Sample_264497.zip
6706 Views

this is the code which i am using on row databound of gridview to sort the columns with arrows..

        protected void grdDetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {
                if (e.Row.RowType == DataControlRowType.Header)
                {

                    GridView senderGridView = (GridView)sender;
                    Literal space = new Literal();
                    space.Text = " ";
                    if (e.Row != null && e.Row.RowType == DataControlRowType.Header)
                    {
                        for (int i = 0; i < grdDetails.Columns.Count; i++)
                        {
                            TableCell cell = e.Row.Cells[i];
                            DataControlField column = grdDetails.Columns[i];

                            if (cell.HasControls())
                            {
                                LinkButton button = cell.Controls[0] as LinkButton;
                                if (button != null)
                                {
                                    Image image = new Image();
                                    if (CurrentSortExpression == column.SortExpression)
                                    {
                                        if (CurrentSortDirection == "asc")
                                            image.ImageUrl = "~/images/asc.png";
                                        else if (CurrentSortDirection == "desc")
                                            image.ImageUrl = "~/images/desc.png";
                                    }
                                    cell.Controls.Add(image);
                                    e.Row.ToolTip = "Sort Data !!!";

                                }
                            }
                        }
                    }
                }

problem is i get the sort arrows but by default i need to show the user that columns can be sorted

this i did in pageload i get a arrow by default in gridview but when change the page index of gridview it disappears as it is in pageload..

TableCell tableCell = grdDetails.HeaderRow.Cells[0];
Image img = new Image();
img.ImageUrl = "~/Images/asc.png";
tableCell.Controls.Add(new LiteralControl("&nbsp;"));
tableCell.Controls.Add(img);

Is there any way to show it by default ??  i need when the page index changing also.. Help??

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 02, 2017 06:38 AM
on Feb 15, 2021 11:55 PM

Hi Babloo18v,

Refer the below code.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True"
    AllowPaging="true" PageSize="2" OnSorting="GridView1_Sorting" 
    onpageindexchanging="GridView1_PageIndexChanging">
    <Columns>
        <asp:TemplateField HeaderText="Id" SortExpression="Id">
            <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
    </Columns>
</asp:GridView>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = BindGridView();
        TableCell tableCell = GridView1.HeaderRow.Cells[0];
        Image img = new Image();
        img.ImageUrl = "~/Images/asc.png";
        tableCell.Controls.Add(new LiteralControl("&nbsp;"));
        tableCell.Controls.Add(img);
        ViewState["tables"] = dt;
    }
}

private DataTable BindGridView()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    GridView1.DataSource = dt;
    GridView1.DataBind();
    return dt;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    string SortDir = string.Empty;
    DataTable dt = new DataTable();
    dt = ViewState["tables"] as DataTable;
    {
        if (dir == SortDirection.Ascending)
        {
            dir = SortDirection.Descending;
            SortDir = "Desc";
        }
        else
        {
            dir = SortDirection.Ascending;
            SortDir = "Asc";
        }
        DataView sortedView = new DataView(dt);
        sortedView.Sort = e.SortExpression + " " + SortDir;
        GridView1.DataSource = sortedView;
        GridView1.DataBind();
        for (int i = 0; i < GridView1.Columns.Count; i++)
        {
            string lbText = ((LinkButton)GridView1.HeaderRow.Cells[i].Controls[0]).Text;
            if (lbText == e.SortExpression)
            {
                TableCell tableCell = GridView1.HeaderRow.Cells[i];
                Image img = new Image();
                img.ImageUrl = (SortDir == "Asc") ? "~/Images/asc.png" : "~/Images/desc.png";
                tableCell.Controls.Add(new LiteralControl("&nbsp;"));
                tableCell.Controls.Add(img);
            }
        }
    }
}

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

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    BindGridView();
    TableCell tableCell = GridView1.HeaderRow.Cells[0];
    Image img = new Image();
    img.ImageUrl = "~/Images/asc.png";
    tableCell.Controls.Add(new LiteralControl("&nbsp;"));
    tableCell.Controls.Add(img);
}

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable = BindGridView()
            Dim tableCell As TableCell = GridView1.HeaderRow.Cells(0)
            Dim img As Image = New Image()
            img.ImageUrl = "~/Images/asc.png"
            tableCell.Controls.Add(New LiteralControl("&nbsp;"))
            tableCell.Controls.Add(img)
            ViewState("tables") = dt
        End If
    End Sub

    Private Function BindGridView() As DataTable
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
        Return dt
    End Function

    Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
        Dim SortDir As String = String.Empty
        Dim dt As DataTable = New DataTable()
        dt = TryCast(ViewState("tables"), DataTable)
        If True Then
            If dir = SortDirection.Ascending Then
                dir = SortDirection.Descending
                SortDir = "Desc"
            Else
                dir = SortDirection.Ascending
                SortDir = "Asc"
            End If

            Dim sortedView As DataView = New DataView(dt)
            sortedView.Sort = e.SortExpression & " " & SortDir
            GridView1.DataSource = sortedView
            GridView1.DataBind()

            For i As Integer = 0 To GridView1.Columns.Count - 1
                Dim lbText As String = CType(GridView1.HeaderRow.Cells(i).Controls(0), LinkButton).Text
                If lbText = e.SortExpression Then
                    Dim tableCell As TableCell = GridView1.HeaderRow.Cells(i)
                    Dim img As Image = New Image()
                    img.ImageUrl = If((SortDir = "Asc"), "~/Images/asc.png", "~/Images/desc.png")
                    tableCell.Controls.Add(New LiteralControl("&nbsp;"))
                    tableCell.Controls.Add(img)
                End If
            Next
        End If
    End Sub

    Public Property dir As SortDirection
        Get

            If ViewState("dirState") Is Nothing Then
                ViewState("dirState") = SortDirection.Ascending
            End If

            Return CType(ViewState("dirState"), SortDirection)
        End Get
        Set(ByVal value As SortDirection)
            ViewState("dirState") = value
        End Set
    End Property

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridView1.PageIndex = e.NewPageIndex
        BindGridView()
        Dim tableCell As TableCell = GridView1.HeaderRow.Cells(0)
        Dim img As Image = New Image()
        img.ImageUrl = "~/Images/asc.png"
        tableCell.Controls.Add(New LiteralControl("&nbsp;"))
        tableCell.Controls.Add(img)
    End Sub

Screenshot