Reputation: 3313
I have the following part in my Page_Load
method:
DropDownList1.Items.Add("Audi");
DropDownList1.Items.Add("BMW");
…
DropDownList1.Items.Add("Ford");
…
DropDownList1.Items.Add("Vauxhall");
DropDownList1.Items.Add("Volkswagen");
…
Some details are that I have a web form that is part of a car sales web site, part of the required functionality is
that users be able to select the manufacturer of vehicles from a drop down list. I created an <asp:DropDownList ... />
control.
My question is how can re-write the code above to use an ArrayList
, that is fully populated as it is instantiated, is sorted into alphabetical order, and is then used to initialise the DropDownList
?
Upvotes: 0
Views: 14221
Reputation: 256
Provided with three option ListItemCollection, Array, IList.
protected void Page_Load(object sender, EventArgs e)
{
//List item collection
ListItemCollection listItemCollection = new ListItemCollection();
listItemCollection.Add("Audi");
listItemCollection.Add("BMW");
listItemCollection.Add("Ford");
listItemCollection.Add("Vauxhall");
listItemCollection.Add("Volkswagen");
CarDropDown.DataSource = listItemCollection;
CarDropDown.DataBind();
//Array
string[] myCollect = { "Audi", "BMW", "Ford", "Vauxhall", "Volkswagen" };
CarDropDown.DataSource = myCollect;
CarDropDown.DataBind();
//IList
List<string> listCollection = new List<string>();
listCollection.Add("Audi");
listCollection.Add("BMW");
listCollection.Add("Ford");
listCollection.Add("Vauxhall");
listCollection.Add("Volkswagen");
CarDropDown.DataSource = listCollection.OrderBy(name => name);
CarDropDown.DataBind();
}
Upvotes: 0
Reputation: 2321
var makes = new List<string>{
"Ford",
"Audi",
"BMW",
"Vauxhall"
};
makes.Sort();
DropDownList1.DataSource = makes;
DropDownList1.DataBind();
Upvotes: 0
Reputation: 107536
Might as well get strongly-typed while we're at it:
var makes = new List<string> {
"Audi",
"BMW",
"Ford",
"Vauxhall",
"Volkswagen"
};
makes.Sort();
DropDownList1.DataSource = makes;
DropDownList1.DataBind();
Upvotes: 5
Reputation: 3231
var makes = new List<string>
{
"BMW",
"Volkswagen",
"Ford",
"Vauxhall",
"Audi",
};
DropDownList1.DataSource = makes.OrderBy(x => x);
DropDownList1.DataBind();
You can also use 'OrderByDescending' to flip it to reverse alpha.
makes.OrderByDescending(x => x);
Upvotes: 0
Reputation: 22323
try:
ArrayList MyArray = new ArrayList();
MyArray.Add("Audi");
MyArray.Add("BMW");
MyArray.Add("Ford");
MyArray.Add("Vauxhall");
MyArray.Add("Volkswagen");
MyArray.Sort();
MyDropDownList.DataSource = MyArray ;
MyDropDownList.DataBind();
Upvotes: 2
Reputation: 5825
private static ArrayList _listOfCars = new ArrayList { "Audi", "BMW", "Ford" };
protected override Page_Load ...
{
DropDownList1.DataSource = _listOfCars;
DropDownList1.DataBind();
}
This should also do what you need it to do. Syntax might not be totally correct, I didn't check it in VS.
Upvotes: 0