简体   繁体   中英

Move list box items from one listbox to another listbox?

I am trying to move listbox items between two listboxes.Before that i created two arrraylists for each listbox.so before moving the listbox item i am trying to add the items to the arraylist. here is the code

 foreach (string st in listbox1.Items)
            {
                arraylist1.Add(st1);
            }

but i am getting an exeption Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.String'.

You're getting this error because listbox1.Items is a ListItemCollection.

foreach (ListItem li in listbox1.Items)
{
    arraylist1.Add(li.Text);
}

foreach (string st in listbox1.Items) should be

 foreach (ListItem st in listbox1.Items) 
           // your code

Try using

foreach (ListItem li in listbox1.Items) 
{     
     arraylist1.Add(li.Text); 
}

ListBox.Items is of ListItemCollection type. It consists of ListItem objects, not strings.

What You are trying to do is:

        foreach (ListItem lstItem in ListBox1.Items)
        {
            arraylist1.Add(lstItem);
        } 

This is because a list item is an object in it's own right and not a string object. So change the string to ListItem in your code above and it should work fine.

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