Innova
Innova

Reputation: 4971

how to add the selected item from a listbox to list <string> in c#

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

Upvotes: 2

Views: 22625

Answers (6)

You can do this in one operation:

IEnumerable<string> groupList = groupsListBox.SelectedItems.Cast<string>();

It will always work for custom objects too:

IEnumerable<CustomObject> groupList = groupListBox.SelectedItems.Cast<CustomObject>();

Upvotes: 0

Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

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

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245429

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

Upvotes: 1

Pankaj
Pankaj

Reputation: 4505

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

Upvotes: 0

ChrisBD
ChrisBD

Reputation: 9209

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

Upvotes: 2

Lee
Lee

Reputation: 144136

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

Upvotes: 8

Related Questions