CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Sorting in Asp.Net ListView control - Binding in CodeBehind   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Sorting in Asp.Net ListView control - Binding in CodeBehind

By Bala Murugan
Posted On Sep 24, 2011
Article Rating: (Login)
Average Rating: 4.5
No of Ratings: 2
No of Comments: 0
Print this article.
Category: ASP.Net

Subscribe to our feed!

Sorting in Asp.Net ListView control - Binding in CodeBehind

My previous article, Sorting in ListView control in Asp.Net - Using DataSource controls demonstrated sorting on the ListView data when using datasource controls. In a real world application, most of the time we will end binding the ListView control ourselves without depending on the datasource controls for variety of reasons.  One of the challenges in providing the sorting feature when we bind the data manually is, the e.SortDirection property will always return Ascending every time when onsorting event is called on ListView control.

Moving forward, let’s understand how to deal with this challenge and implement a working sorting feature on the ListView control when manually binding the data from codebehind file.

Similar to my previous article, I will demonstrate sorting in two different ways,

1.      Sorting ListView by clicking the header link

2.      Sorting ListView by clicking up and down arrow image

 

I will also use the same database table and ListView layout which we used in the previous part in this article too.

To understand this article, I assume you have created a new Asp.Net project using C# as language in your visual studio 2008.

 

Sorting ListView by clicking the header link

Drag a ListView control from the data tab of your visual studio 2008. Configure the LayoutTemplate and ItemTemplate of ListView control to display the data. Like I said earlier, I will use tabular format in this article. Read the article ListView Control in ASP.Net 3.5 if you are new to ListView control. To make a column sortable, we need to define the header as a LinkButton by setting its CommandArgument property to the database column name and CommandName to “Sort”. When this settings, it will fire onsorting event of ListView control whenever the header text is clicked. Refer the below code,

ASPX

<asp:ListView ID="lvEmployee" runat="server" DataKeyNames="EmpID" onsorting="lvEmployee_Sorting">

<LayoutTemplate>         

    <table ID="itemPlaceholderContainer" border="1">

        <tr id="Tr2">

            <th id="Th1">

                <asp:LinkButton ID="lbEmpID" CommandArgument="EMPID" CommandName="Sort" Text="EmpID" runat="server" />

                </th>

            <th id="Th2">                                   

                 <asp:LinkButton ID="lbEmpName" CommandArgument="EMPNAME" CommandName="Sort" Text="EmpName" runat="server" />

                 </th>

            <th id="Th3">

                Department</th>

            <th id="Th4">

                Age</th>

            <th id="Th5">

                Address</th>

        </tr>

        <tr ID="itemPlaceholder" runat="server">

        </tr>

    </table>                   

 </LayoutTemplate>

<ItemTemplate>

   <tr>

    <td>

        <asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("EmpID") %>' />

    </td>

    <td>

        <asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>' />

    </td>

    <td>

        <asp:Label ID="DepartmentLabel" runat="server"

            Text='<%# Eval("Department") %>' />

    </td>

    <td>

        <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />

    </td>

    <td>

        <asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />

    </td>

</tr>

</ItemTemplate>

</asp:ListView>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

            BindLV("");

    }

    public DataTable GetEmployee(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dtEmp = new DataTable();

        ada.Fill(dtEmp);

        return dtEmp;

    }

    private void BindLV(string SortExpression)

    {

        lvEmployee.DataSource = GetEmployee("Select * from Employee" + SortExpression);

        lvEmployee.DataBind();

    }

 

    protected void lvEmployee_Sorting(object sender, ListViewSortEventArgs e)

    {

        LinkButton imEmpID = lvEmployee.FindControl("imEmpID") as LinkButton;

        LinkButton imEmpName = lvEmployee.FindControl("imEmpName") as LinkButton;

 

        string SortDirection = "ASC";

 

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

        {

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

            {

                ViewState["SortExpression"] = null;

                SortDirection = "DESC";               

            }

            else

            {

                ViewState["SortExpression"] = e.SortExpression;

            }

        }

        else

        {

            ViewState["SortExpression"] = e.SortExpression;

        }

        BindLV(" order by " + e.SortExpression + " " + SortDirection);

    }

 

In the above code, I have made EmpID and EmpName columns to be sortable in the ListView control. Since e.SortDirection property will not remember the correct sort direction, I have used ViewState to hold the last sort expression to manipulate the sort direction in onsorting event. That’s it! Execute the application and see it in action. Refer the below screen shot for the output.

Sort ListView based on Arrow image in header

 



ASP.Net Hosting

Recent Articles

Sorting ListView by clicking up and down arrow image

We can display up/down arrow image to indicate the sort direction by doing small code change and including some more code in onsorting event. This approach will give a better understanding on the action the user intend to perform on the ListView control when compared to the previous approach discussed in the previous section.

ASPX

<asp:ListView ID="lvEmployee" runat="server" DataKeyNames="EmpID" onsorting="lvEmployee_Sorting">

<LayoutTemplate>          

    <table ID="itemPlaceholderContainer" border="1">

        <tr id="Tr2">

            <th id="Th1">

                EmpID

                 <asp:ImageButton ID="imEmpID" CommandArgument="EMPID" CommandName="Sort" ImageUrl="~/img/asc.png" runat="server" /></th>

            <th id="Th2">

                EmpName

                 <asp:ImageButton ID="imEmpName" CommandArgument="EMPNAME" CommandName="Sort" ImageUrl="~/img/asc.png" runat="server" /></th>

            <th id="Th3">

                Department</th>

            <th id="Th4">

                Age</th>

            <th id="Th5">

                Address</th>

        </tr>

        <tr ID="itemPlaceholder" runat="server">

        </tr>

    </table>

 </LayoutTemplate>

<ItemTemplate>

   <tr>

    <td>

        <asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("EmpID") %>' />

    </td>

    <td>

        <asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>' />

    </td>

    <td>

        <asp:Label ID="DepartmentLabel" runat="server" Text='<%# Eval("Department") %>' />

    </td>

    <td>

        <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />

    </td>

    <td>

        <asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />

    </td>

 </tr>

</ItemTemplate>

</asp:ListView>

CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

            BindLV("");

    }

    public DataTable GetEmployee(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dtEmp = new DataTable();

        ada.Fill(dtEmp);

        return dtEmp;

    }

    private void BindLV(string SortExpression)

    {

        lvEmployee.DataSource = GetEmployee("Select * from Employee" + SortExpression);

        lvEmployee.DataBind();

    }

 

    protected void lvEmployee_Sorting(object sender, ListViewSortEventArgs e)

    {

        ImageButton imEmpID = lvEmployee.FindControl("imEmpID") as ImageButton;

        ImageButton imEmpName = lvEmployee.FindControl("imEmpName") as ImageButton;

 

        string DefaultSortIMG = "~/img/asc.png";

        string imgUrl = "~/img/desc.png";

 

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

        {

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

            {

                ViewState["SortExpression"] = null;

                imgUrl = DefaultSortIMG;

            }

            else

            {

                ViewState["SortExpression"] = e.SortExpression;

            }

        }

        else

        {

            ViewState["SortExpression"] = e.SortExpression;

        }

 

        switch (e.SortExpression)

        {

            case "EMPID":

                if (imEmpName != null)

                    imEmpName.ImageUrl = DefaultSortIMG;

                if (imEmpID != null)

                    imEmpID.ImageUrl = imgUrl;

                break;

            case "EMPNAME":

                if (imEmpID != null)

                    imEmpID.ImageUrl = DefaultSortIMG;

                if (imEmpName != null)

                    imEmpName.ImageUrl = imgUrl;

                break;

        }

        BindLV(" order by " + e.SortExpression + " " + ((ViewState["SortExpression"]!=null) ? "ASC" : "DESC"));

    }

In the above code, I am toggling the arrow images depending on the value stored in ViewState i.e. if the new sort expression is same as the previous sort expression (or the one stored in viewstate) then the sort order is descending.

That’s it! Execute the application and see it in action. Once executed, you will see an output similar to below,

Sort ListView based on Arrow image in header

Download the source attached with this article and see it in action.

 

Downloads

Download Source

 

Conclusion

Sorting is one of the very useful and most often repeated tasks we will do in any data display control. This article will help you to implement it in ListView control which is the default choice when it comes to data display these days. I have demonstrated sorting in ListView control when without using datasource controls in this article. To do the same without using data source control, refer the below article,

Sorting in ListView control in Asp.Net - Using DataSource controls

Download the attachment in this article and see it in action.

 

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments