我的Page_Load
方法中有以下部分:
DropDownList1.Items.Add("Audi");
DropDownList1.Items.Add("BMW");
…
DropDownList1.Items.Add("Ford");
…
DropDownList1.Items.Add("Vauxhall");
DropDownList1.Items.Add("Volkswagen");
…
一些细节是我有一个网络表单,它是汽车销售网站的一部分,是所需功能的一部分
用户可以从下拉列表中选择车辆制造商。我创建了一个<asp:DropDownList ... />
控件。
我的问题是如何重新编写上面的代码以使用ArrayList
,它在实例化时完全填充,按字母顺序排序,然后用于初始化DropDownList
?
答案 0 :(得分:4)
当我们接触它时,不妨强烈打字:
var makes = new List<string> {
"Audi",
"BMW",
"Ford",
"Vauxhall",
"Volkswagen"
};
makes.Sort();
DropDownList1.DataSource = makes;
DropDownList1.DataBind();
答案 1 :(得分:2)
尝试:
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();
答案 2 :(得分:0)
private static ArrayList _listOfCars = new ArrayList { "Audi", "BMW", "Ford" };
protected override Page_Load ...
{
DropDownList1.DataSource = _listOfCars;
DropDownList1.DataBind();
}
这也应该做你需要做的事情。语法可能不完全正确,我没有在VS中检查它。
答案 3 :(得分:0)
var makes = new List<string>
{
"BMW",
"Volkswagen",
"Ford",
"Vauxhall",
"Audi",
};
DropDownList1.DataSource = makes.OrderBy(x => x);
DropDownList1.DataBind();
您还可以使用&#39; OrderByDescending&#39;翻转它以反转alpha。
makes.OrderByDescending(x => x);
答案 4 :(得分:0)
var makes = new List<string>{
"Ford",
"Audi",
"BMW",
"Vauxhall"
};
makes.Sort();
DropDownList1.DataSource = makes;
DropDownList1.DataBind();
答案 5 :(得分:0)
提供三个选项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();
}