In this article I will explain how to implement sorting in repeater control using Linq and this is a simple way of sorting within the repeater control.
Download source code for Sorting in Repeater control using Linq.
In order to understand this article, better to download the source code and read it.
- The aspx
page should have following code.
<div> <table border="1" width="60%"> <tr style="backgroundcolor:#669acc;"> <td>ID <asp:LinkButton ID="LinkButton3"runat="server" onclick="LinkButton3_Click"> <img src="arrowdown.GIF" alt="descending"/></asp:LinkButton> <asp:LinkButton ID="LinkButton1" runat="server"onclick="LinkButton1_Click"> <img src="arrowup.GIF" alt="ascending"/></asp:LinkButton></td> <td>Name </td> <td>Country </td></tr> <asp:RepeaterID="Repeater1" runat="server"><ItemTemplate> <tr style="background-color:#f2f7fd;"> <td ><%# Eval("sortid") %></td><td><%# Eval("Name")%></td> <td><%# Eval("Country")%></td></tr></ItemTemplate> </asp:Repeater></table> </div>
- In this article, I have used a Repeater and two Link Buttons are used.
- The Code behind file looks
like:
- ConDB() is the method for the connection string you can find it in
connection.cs class.
connection cnn = new connection();
private void BindRepeater()
{
using (var db = cnn.ConDB())
{
var select = from table in db.SortTables select table;
Repeater1.DataSource = select;
Repeater1.DataBind();
}}
- Above code is used to bind the repeater with the datasource. If you call the above code the output looks like

Sorting is done while binding the datasource to the
repeater. You can sort the columns based on column you want to sort. Here I used ID column to sort the records.
private void sortDescending()
{
using (var db = cnn.ConDB())
{
var select = from sort in db.SortTables
select sort;
Repeater1.DataSource = select.OrderByDescending(item => item.SortID);
Repeater1.DataBind();
LinkButton3.Visible = false;
LinkButton1.Visible = true;
}
}
- select.OrderByDescending is used to display the records in descending order.
If the above code is called, the output looks as

You can observe the rows are changed according to the
descending order of the ID column.
Similarly you can also sort in ascending order using below
code
private void sortAscending()
{
using (var db = cnn.ConDB())
{
var select = from sort in db.SortTables
select sort;
Repeater1.DataSource = select.OrderBy(item => item.SortID);
Repeater1.DataBind();
LinkButton1.Visible = false;
LinkButton3.Visible = true;
}
}
select.OrderBy is used to display the records in ascending order. If the above code is called the columns are
arranged in ascending order and the output looks as

For the complete code please check the attached file.
Conclusion
- In this article I have explained about How to bind repeater and
sort the columns in the repeater using Linq. Hope you like this article, please vote for it if you like this article. Thanks

About the Author