Reputation: 241
I have a DropDownList
, and the items in the list is as follows:
Bedroom
Kitchen
Garden
So after choosing any one item from the above list, I have a TextBox
, in which a number is given. Therefore depending on the number given in the TextBox
, the number of Locations is going to be added to the CheckBoxList
.
For example, If I select "Bedroom" and give the number as "3", the CheckBoxList
items will be as follows:
Bedroom1
Bedroom2
Bedroom3
The problem I am facing is, since any random item can be deleted from the CheckBoxList
, the items are not sorted. For example, if I delete "Bedroom2", the list items will be:
Bedroom1
Bedroom3
And if again "Bedroom" is selected from DropDownList
and a number is given for example "2", the items in the CheckBoxList
will be:
Bedroom1
Bedroom3
Bedroom1
Bedroom2
This is the same problem no matter I select any item from the DropDownList
.
So can someone kindly help me on the sorting of these items how ever it is added. It should be sorted according w.r.t each location in the DropDownList
.
Upvotes: 1
Views: 8139
Reputation: 8696
You can add items to ArrayList before adding them to CheckBoxList. Then sort array list then give DataSource to CheckBoxList and DataBind()
if(!Page.IsPostBack)
{
//Create two ArrayLists for sorting items
ArrayList listItems1 = new ArrayList();
ArrayList listItems2 = new ArrayList();
int q1=Convert.ToInt16(TextBox1.Text);
for (int i = 1; i <= q1; i++)
{
string t1 = DroDownList1.SelectedItem.ToString().Trim();
//Add items hereusing .Add() method of ArrayList
listItems1.Add(string.Concat(t1, i));
listItems2.Add(DropDownList1.SelectedItem.Text);
}
//Sort your items using .Sort() method of ArrayList
listItems1.Sort()
listItems2.Sort()
//Bind your items to your CheckBoxLists
CheckBoxList1.DataSource = listItems1;
CheckBoxList2.DataSource = listItems2;
CheckBoxList1.DataBind();
ChackBoxList2.DataBind();
}
This is original link.
Upvotes: 0
Reputation: 1332
Try this
var items = CheckBoxList1.Items
.Cast<ListItem>()
.OrderBy(i=>i.Text)
.ToArray();
CheckBoxList1.Items.Clear();
CheckBoxList1.Items.AddRange(items);
Upvotes: 7