views:

81

answers:

5

how to add the selected item from a listbox to list to get the username that are selected

my code:

        List<String> lstitems = new List<String>();

        foreach (string str in lstUserName.SelectedItem.Text)
        {
            lstitems.Add(str);
        }

it show me error saying cannot convert char to string.... how to add the items to list or array

+4  A: 

You need to use the SelectedItems property instead of SelectedItem:

foreach (string str in lstUserName.SelectedItems) 
{ 
    lstitems.Add(str); 
} 

EDIT: I just noticed this is tagged asp.net - I haven't used webforms much but looking at the documentation it seems this should work:

List<string> listItems = listBox.GetSelectedIndices()
    .Select(idx => listBox.Items[idx])
    .Cast<string>()
    .ToList();
Lee
If he's using ASP.NET and binding properly, instead of casting the whole Item to a string the OP would probably just want the Value from the Item.
Justin Niessner
+1  A: 

If there's only one selected item:

List<String> lstitems = new List<String>();

lstitems.Add(lstUsername.SelectedItem.Value);

Here's a method for getting multiple selections since System.Web.UI.WebControls.ListBox doesn't support SelectedItems:

// Retrieve the value, since that's usually what's important
var lstitems = lstUsername.GetSelectedIndices()
                          .Select(i => lstUsername.Items[i].Value)
                          .ToList();

Or without LINQ (if you're still on 2.0):

List<string> lstitems = new List<string():

foreach(int i in lstUsername.GetSelectedIndices())
{
    lstitems.Add(lstUsername[i].Value);
}
Justin Niessner
+1  A: 

I note that you're using ASP.

For standard C# the following would work:

    List<string> stringList = new List<string>();
    foreach (string str in listBox1.SelectedItems)
    {
        stringList.Add(str);
    }
ChrisBD
A: 

You can also do this

 List<String> lstitems = new List<String>();

        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected)
                lstitems.Add(ListBox1.Items[i].Value);
        }
Pankaj
A: 

If you are using a button to add selected 'item' in string list, just do this.

    private void button1_Click(object sender, EventArgs e)
    {
        List<string> selectedItems = new List<string>();

        string item = listBox1.SelectedItem.ToString();

        if (!selectedItems.Contains(item))
        {
            selectedItems.Add(item);
        }
    }
Serkan Hekimoglu