The ASP.NET SortedList is a collection of items having key and value pairs. It’s a combination of ArrayList and Hashtable. Here, the items appear sorted automatically and one can add item using ‘Add()’ method.
[csharp]SortedList spSortedList = new SortedList();
spSortedList.Add("1", "Sunday");
spSortedList.Add("2", "Monday");
spSortedList.Add("3", "Tuesday");
spSortedList.Add("4", "Wednesday");
spSortedList.Add("5", "Thursday");
spSortedList.Add("6", "Friday");
spSortedList.Add("7", "Saturday");[/csharp]
This SortedList is also used as data source for data binding controls like RadioButtonList, CheckBoxList,DropDownList etc.
Example
In the below example, on clicking a button one CheckBoxList is populated with days of a week and the data source for this CheckBoxList is a SortedList.
In designer, one Button control and one CheckBoxList has been added.
In ‘Default.aspx.cs’ page, under ‘spButton_Click’ event the code has been written to add days to the spSortedList using ‘Add()’ method.
[csharp]protected void spButton_Click(object sender, EventArgs e)
{
SortedList spSortedList = new SortedList();
spSortedList.Add("1", "Sunday");
spSortedList.Add("2", "Monday");
spSortedList.Add("3", "Tuesday");
spSortedList.Add("4", "Wednesday");
spSortedList.Add("5", "Thursday");
spSortedList.Add("6", "Friday");
spSortedList.Add("7", "Saturday");
spCheckBoxList.DataSource = spSortedList;
spCheckBoxList.DataValueField = "key";
spCheckBoxList.DataTextField = "value";
spCheckBoxList.DataBind();
}[/csharp]
When viewed the aspx in browser, one will get the following screens. At first, only the button will appear in the page. On clicking the button, the CheckBoxList will be shown with the days.