我有一个asp:Listbox
我需要根据用户选择切换项目。这是我尝试过的:
string[] my2012Departments = new string[5];
my2012Departments[0] = "Administration";
my2012Departments[1] = "Imaging Services";
my2012Departments[2] = "IT";
my2012Departments[3] = "Lab";
my2012Departments[4] = "Support Services";
lstDSYDepartment.Items.AddRange(my2012Departments.ToArray());
//The AddRange will also not work without .ToArray()
然而,这会导致以下错误:
1。无法转换为' string []'到' System.Web.UI.WebControls.ListItem []'
2.最佳重载方法匹配.... AddRange ....有一些无效的参数
根据the documentation,只要我将代码放在表单加载中,这应该可以工作。
答案 0 :(得分:2)
您可以创建List<string>
并将其指定为列表框的数据源,如下所示
List<string> my2012Departments = new List<string>();
my2012Departments.Add("Administration");
my2012Departments.Add("Imaging Services");
my2012Departments.Add("IT");
my2012Departments.Add("Lab");
my2012Departments.Add("Support Services");
lstDSYDepartment.DataSource = my2012Departments;
lstDSYDepartment.DataBind();
(OR)而不是分配字符串数组;创建一个ListItem[]
数组,如下所示
ListItem[] my2012Departments = new ListItem[5];
my2012Departments[0] = "Administration";
my2012Departments[1] = "Imaging Services";
my2012Departments[2] = "IT";
my2012Departments[3] = "Lab";
my2012Departments[4] = "Support Services";
this.lstDSYDepartment.Items.AddRange(my2012Departments);
答案 1 :(得分:0)
您引用的文档适用于Windows窗体,而不适用于ASP。
尝试
lstDSYDepartment.Items.Add("Administration");
lstDSYDepartment.Items.Add("Imaging Services");
...