Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

I decided to write this example because this has been asked many times at the forums. In this article, I will show on how to sort GridView columns manually using a DataTable.

Note that in this example, I used my own database for populating the GridView.  See Adding Rows in GridView for more info.

Now to get started lets set up the GridView with TemplateField columns.  Since we are working with TemplateFields then we need to handle sorting manually by adding a LinkButton control inside the HeaderTemplate of the TemplateField column.

Note that for the simplicity of this demo, I will show only a single column just for your reference. You can apply the same way mentioned in this example to the other template columns in your GridView that you wan’t to Sort based on your requirements.

Below is the GridView Column mark up:

       <asp:TemplateField>

            <HeaderTemplate>

                <asp:LinkButton ID="LinkButtonEmpName" runat="server" Text="Employee Name" CommandName="Sort" CommandArgument="Employees">

                </asp:LinkButton>

            </HeaderTemplate>

            <ItemTemplate>

                <asp:Label ID="LabelEmployee" runat="server" Text='<%# Bind("Employees") %>'/>

            </ItemTemplate>

            <FooterTemplate>

                <asp:TextBox ID="TextBoxEmployee" runat="server"/>

            </FooterTemplate>

        </asp:TemplateField >

 

As you can see I have added a LinkButton under the HeaderTemplate section of the TemplateField and set the CommandName and CommandArgument of the LinkButton.

Since we need to perform sorting manually then we set the value of CommanName to “Sort” so that we can perform certain actions "like sorting" based on that value at RowCommand event later. Also be sure to set the CommandArgument value, the value of the CommandArgument should be the Field Name from your database table that corresponds to a particular column. Like for example in the above declaration, I set the CommandArgument value to “Employees”.

Now let’s proceed to the code behind part of the webform and create the method for binding the GridView. Here are the code blocks below:

    private string GetConnectionString()

    {

        //Where DBConnection is the connetion string that was set up in the web config file

        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

    }

 

    private void BindGridView()

    {

        DataTable dt = new DataTable();

       

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT * FROM Table1";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);

            if (dt.Rows.Count > 0)

            {

                DataView dv = dt.DefaultView;

                if (this.ViewState["SortExpression"] != null)

                {

                    dv.Sort = string.Format("{0} {1}", ViewState["SortExpression"].ToString(), this.ViewState["SortOrder"].ToString());

                }

 

                GridViewEmployee.DataSource = dt;

                GridViewEmployee.DataBind();

            }

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            BindGridView();

        }

    }

 

 

For more detail information about Binding the GridView with data then you can refer here:  Adding Rows in GridView. Basically what is added in the code above is the sorting functionality using a DataView. Since a LinkButton triggers a postback then we have to maintain the Sort Expression and Sorting Order in the ViewState variables. So if the Sort Expression is available, then the DataView’s Sort property will be set with the ViewState’s SortExpression and SortOrder values.

Now let’s implement the Sorting functionality at RowCommand event. For those who do not know on how to generate the Event in GridView then you can follow these steps below:

Switch to Design View in Visual Studio Designer

  • Click on the GridView
  • Navigate to the GridView Property Pane and then SWITCH to Event Properties
  • From there you would be able to find the RowCommand event
  • Double Click on that to generate the Event handler for you
  • Then write the codes there

Here’s the code block below for the RowCommand event:

    protected void GridViewEmployee_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName.Equals("Sort"))

        {

            if (ViewState["SortExpression"] != null)

            {

                if (this.ViewState["SortExpression"].ToString() == e.CommandArgument.ToString())

                {

                    if (ViewState["SortOrder"].ToString() == "ASC")

                        ViewState["SortOrder"] = "DESC";

                    else

                        ViewState["SortOrder"] = "ASC";

                }

                else

                {

                    ViewState["SortOrder"] = "ASC";

                    ViewState["SortExpression"] = e.CommandArgument.ToString();

                }

               

            }

            else

            {

                ViewState["SortExpression"] = e.CommandArgument.ToString();

                ViewState["SortOrder"] = "ASC";

            }

        }

        //Re Bind The Grid to reflect the Sort Order

        BindGridView();

    }

 

Basically, the code above store’s the current Order and Sort Expression in the ViewState. This means that if the column was sorted in ascending order then the new direction has to be descending.

Running the code above will show something like this in the page:


Now clicking on the Employee Name Header will sort the Column like this below:

As you can see the Data in the first column changes the order to descending.

That's it! Hope you will find this example useful!


Technorati Tags: ,,,
Posted on Sunday, July 12, 2009 4:58 PM ADO.NET , ASP.NET , C# , GridView | Back to top


Comments on this post: Sorting GridView Manually with TemplateFields

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
Hello,

I've done exactly that but getting error:

The GridView 'GridView3' fired event Sorting which wasn't handled.

I've assumed the following tag on Gridview: OnRowCommand="GridView3_RowCommand"

Shouldnt be OnSorting=GridView3_Sorting?
Left by Tiago Machado on Nov 19, 2009 9:58 AM

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
Thanks for your reply.

So should I set on GridView RowCommand event?
Left by Tiago Machado on Nov 29, 2009 6:25 AM

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
dv.Sort = string.Format("{0} {1}", ViewState["SortExpression"].ToString(), this.ViewState["SortOrder"].ToString());

Error is:- "Cannot find column Employees." help pls
Left by RAman on Oct 19, 2010 8:09 PM

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
Good Yaar,U solve my problem
Left by Raman on Oct 19, 2010 8:22 PM

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
Thanks
Left by Satyajeet on Jul 15, 2011 7:08 PM

# A working demo would be great
Requesting Gravatar...
your demonstration is cool but I still can not follow it because I can not connect certain dots. It would be great if you can put downloadable code as demo. Thanks
Left by joji on Oct 11, 2011 9:06 PM

# re: Sorting GridView Manually with TemplateFields
Requesting Gravatar...
thanks a lot for saving the time
Left by sathwik on Jul 23, 2012 8:45 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net