Reputation: 2215
I have an asp:Listbox
that I need to switch out the items on depending on user selection. Here is what I have tried:
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()
This however causes the following errors:
1. Cannot Convert from 'string[]' to 'System.Web.UI.WebControls.ListItem[]'
2.The best overloaded method match for ....AddRange.... has some invalid arguments
According to the documentation this should work as long as I put the code in the form load.
Upvotes: 0
Views: 1524
Reputation: 77846
You can create a List<string>
and assign that as the datasource for your listbox like below
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) Instead of assigning a string array; create a array of ListItem[]
like below
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);
Upvotes: 2
Reputation: 32566
The documentation you refer to is for Windows Forms, not for ASP.
Try
lstDSYDepartment.Items.Add("Administration");
lstDSYDepartment.Items.Add("Imaging Services");
...
Upvotes: 0