Sorting dropdown list can be easily done using Linq. In this post I am going to
tell how you can sort the dropdown list based on DataTextField and
DataValueField using Linq.
Source for dropdown list:
<asp:DropDownList
ID="DropDownList1"
runat="server">
</asp:DropDownList
DataBase table has columns SortID,Name and Country with following values:
![1.gif]()
Binding the dropdown list with the datasource
private
void populateDataText()
{
using (var
db = cnn.ConDB())
{
var select =
from table in
db.SortTables
select table;
DropDownList1.DataSource = select.OrderBy(item=>item.SortID);
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "SortID";
DropDownList1.DataBind();
}
}
In the above code the dropdown list is sorted based on the SortID, when we call
the populateDropDown()the dropdown list looks like
![2.gif]()
If you want to sort the dropdown list based on the Name then call the following
private
void populateDataValue()
{
using (var
db = cnn.ConDB())
{
var select =
from table in
db.SortTables
select table;
DropDownList1.DataSource = select.OrderBy(item => item.Name);
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "SortID";
DropDownList1.DataBind();
}
}
The output looks as:
![3.gif]()
By a simple change in code you can sort based on DataTextField or DataValueField
and you can also sort in the descending order by using
select. OrderByDescending (item => item.Name);
Thanks !
Hope this helps.