简体   繁体   中英

How do I populate a 'asp:ListBox' with an array of strings?

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.

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);

The documentation you refer to is for Windows Forms, not for ASP.

Try

lstDSYDepartment.Items.Add("Administration");
lstDSYDepartment.Items.Add("Imaging Services");
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM