none
How to get multiple selected values and items from listbox ?

    Question

  • Hi people,

    how do i extract out the selected items and values from a multiple selected enabled listbox through C# code ?

    Monday, November 21, 2005 9:37 AM

Answers

  • This is an example using strings as the objects in the listbox.

    Windows application in C# and I added a listbox and a button.



            private void Form1_Load(object sender, System.EventArgs e)
            {
                listBox1.Items.Add("Item1");
                listBox1.Items.Add("Item2");
                listBox1.Items.Add("Item3");
                listBox1.Items.Add("Item4");
                listBox1.Items.Add("Item5");
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                String strItem;
                foreach(Object selecteditem in listBox1.SelectedItems)
                {
                    strItem = selecteditem as String;
                    System.Diagnostics.Debug.WriteLine(strItem);
                    //Process(strItem);
                }
            }

     

    Monday, November 21, 2005 6:42 PM

All replies

  • You can use the SelectedItems property. It will give you a collection of all selected items.
    Monday, November 21, 2005 10:17 AM
  •  Andreas Johansson wrote:
    You can use the SelectedItems property. It will give you a collection of all selected items.


    Hi Andreas,

    thanks for the reply, yup this is where i am stuck, how do i actually reiterate throigh the collection to obtain the items and values ?
    Monday, November 21, 2005 3:46 PM
  • You can do a for or a ForEach. And SelectedItem[index] get you the item in the index.
    Monday, November 21, 2005 6:34 PM
  • This is an example using strings as the objects in the listbox.

    Windows application in C# and I added a listbox and a button.



            private void Form1_Load(object sender, System.EventArgs e)
            {
                listBox1.Items.Add("Item1");
                listBox1.Items.Add("Item2");
                listBox1.Items.Add("Item3");
                listBox1.Items.Add("Item4");
                listBox1.Items.Add("Item5");
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                String strItem;
                foreach(Object selecteditem in listBox1.SelectedItems)
                {
                    strItem = selecteditem as String;
                    System.Diagnostics.Debug.WriteLine(strItem);
                    //Process(strItem);
                }
            }

     

    Monday, November 21, 2005 6:42 PM
  •  Andreas Johansson wrote:
    This is an example using strings as the objects in the listbox.

    Windows application in C# and I added a listbox and a button.



            private void Form1_Load(object sender, System.EventArgs e)
            {
                listBox1.Items.Add("Item1");
                listBox1.Items.Add("Item2");
                listBox1.Items.Add("Item3");
                listBox1.Items.Add("Item4");
                listBox1.Items.Add("Item5");
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                String strItem;
                foreach(Object selecteditem in listBox1.SelectedItems)
                {
                    strItem = selecteditem as String;
                    System.Diagnostics.Debug.WriteLine(strItem);
                    //Process(strItem);
                }
            }

     



    Hi Andreas thanks for the example it really help greatly..How would i extract the associated selected value associated with each item as i iterate through the collection ? And does the method exist for .NET forms ? Because i am trying todebug a web based application that was written in c#
    Tuesday, November 22, 2005 2:14 AM
  • That will be quite different actually. ListBox in ASP.NET has no SelectedItems property. But it has a collection of ListItem that you can iterate through and see what is selected and not



        foreach(ListItem listItem in listBox1.Items)
        {
           if (listItem.Selected == True)
           {
              //listItem.Value contains the value of the selected item
              //listItem.Text is the text displayed in the listbox of the selected item
           }
        }


     
    Tuesday, November 22, 2005 8:32 AM
  • Maybe this can be useful for others dealing with lisbox selected values

    If you have DataSource for that listBox use this.

    foreach (DataRowView objDataRowView in listBox1.SelectedItems)

    {

                MessageBox.Show("My value: " + objDataRowView["id"].ToString());

    }

    Crazy man its working!!!

    Monday, August 14, 2006 10:43 PM
  • Hallo, i've got the same problem and i work with .net Framework 1.1, how can i do?
    Tuesday, June 12, 2007 1:20 PM
  •  Mitch0820 wrote:
    Hallo, i've got the same problem and i work with .net Framework 1.1, how can i do?

     

    The SelectedItems property should be supported in 1.1 also. What problem are you experiencing?

    Tuesday, June 12, 2007 2:35 PM
  • I work with .Net Framework 1.1 and with Asp.Net ListBox and there isn't the SelectedItems property.

    The SelectionMode property of the ListBox is set to "Multiple" but if i select multiple rows and i loop for all the items only the first selected items is marked as selected.

     

     

     

     

    Wednesday, June 13, 2007 7:28 AM
  • If you look at my third reply in this thread it is for ASP.NET.

     

    Code Snippet

    foreach(ListItem listItem in listBox1.Items)
     {
        if (listItem.Selected == True)
        {
          
    //listItem.Value contains the value of the selected item
           //listItem.Text is the text displayed in the listbox of the selected item
        }
     }

     

    If you have any further questions regarding ASP.NET development and its controls you should check out the ASP.NET forums that cover ASP.NET web development.

    http://forums.asp.net

     

    Thursday, June 14, 2007 8:01 AM
  • So how to get the selected VALUES in a ListBox in windows form? I don't want the text, I don't want the index, I just want the values of the selected items. How can this be done?

     

     

    Sunday, June 24, 2007 12:38 PM
  •  Ashraf Gawdat wrote:

    So how to get the selected VALUES in a ListBox in windows form? I don't want the text, I don't want the index, I just want the values of the selected items. How can this be done?

     

     

    Use the SelectedIndices property instead of SelectedItems.

    Monday, June 25, 2007 8:30 AM
  •  Andreas Johansson wrote:
     Ashraf Gawdat wrote:

    So how to get the selected VALUES in a ListBox in windows form? I don't want the text, I don't want the index, I just want the values of the selected items. How can this be done?

     

     

    Use the SelectedIndices property instead of SelectedItems.

    Sorry but it seems you didn't get what I mean. I want the VALUES of the selected items, not the indices. If I am using a ComboBox I will get the selected value using ComboBox.SelectedValue property. That is what I want when using ListBox but in plural, something like SelectedValues. Unfortunately there is only a SelectedValue property in ListBox control, which gets the value of the first selected item only, but there is no SelectedValuesCollection or such property, which is really strange, because the main difference between ComboBox and ListBox is the multiselection capability!! How can I use the ListBox control if I can't collect the values of the items the user had selected?!

    Monday, June 25, 2007 11:35 AM
  • Sorry, I misunderstood your post.

    How you get the value depends on how you actually store the value for an item. A common way I use for not databound listboxes is to make a ListBoxItem class/structure that has two values, the description and the value.

    Override ToString() to return the description.

    Add an instance of the class/structure to the items collection.

    Use the SelectedItems method to get a collection of ListBoxItems and you can iterate through the returned collection and extract the value of each selected ListBoxItem class/struct.


    Monday, June 25, 2007 3:34 PM
  • Ok, if that works for not databound ListBoxes - I actually didn't try it because I use databinding - is there any other way to achieve this in databound ListBoxes?
    Tuesday, June 26, 2007 9:04 AM
  • When I bind a listbox to a datatable the items are of type DataRowView. This object will let you get to the DataRow that you can use to get any column.
    Wednesday, June 27, 2007 12:54 AM
  • It seems that i'm having the same problem.

     

    How do I get the values from the databound listbox? Can you give a sample code using the datarow ? I'm using VB .net 2.0

     

    I used the selectedindices and I've tested the collection of indices and indeed, it has the indices of those items I selected from the listbox. Problem now is , how do i get the corresponding value for each index? It seems that it's not as easy as listbox1.items.item(indexfromselectedindices)

     

    Any help will be appreciated.

    Wednesday, July 25, 2007 6:48 AM
  • Oh yes I got it....

     

    thanks to the datarow hint

     

    code:

     

    Dim chkList As ListBox.SelectedIndexCollection

    Dim i As Integer = 0

    chkList = lbTemplatesNew.SelectedIndices 'holds the index # of those that were selected

     

    For i = 0 To chkList.Count - 1

    Try

      Dim j As Integer

      Dim sdr As System.Data.DataRowView                     'To represent the bound items in list box

      j = chkList.Item(i)                                                         'the current index# from the collection of selected indices

     MsgBox("the current index# is : " & j)

     sdr = lbTemplatesNew.Items.Item(j)                            'right side of equation returns System.Data.Datarowview

     MsgBox("value : " & sdr.Item(0))

    Catch ex As Exception

     

    End Try

     

    Next

     

    Wednesday, July 25, 2007 7:05 AM
  • Oye Thank You Dost,

     

    Its working fine.

     

     

    Anil Chauhan

     

    Monday, September 15, 2008 8:46 AM
  • Here's a similar way if you don't care for the index.
       'fills out a text box with results in this example   
    Dim x As String = String.Empty  
    Try 
       For Each drv As System.Data.DataRowView In Me.ListBox1.SelectedItems  
           x &= drv.Item(0).ToString & vbCrLf     'column 0 value  
           'use: item(1), item(2), etc. for the other columns  
       Next 
    Catch ex As IndexOutOfRangeException  
     
    End Try 
     
    Me.TextBox1.Text = x 

    • Proposed as answer by h0us3 Saturday, September 05, 2009 5:06 AM
    Thursday, January 22, 2009 5:57 AM
  • It works, thank you very much, I spent more time for this problem, thanks!!!
    Friday, March 13, 2009 4:35 AM
  • Man this realy works
    there any way to know which are the columns in dataview?
    In addition to querying the database?
    Saturday, September 05, 2009 5:08 AM
  •  

     

    ' This Code will give you selected item's index of listbox
    
    If OptChrgAll.Checked = False Then
    
    Dim x As Object
    
    For Each x In LstChrg.SelectedItems
    
    MsgBox(LstChrg.Items.IndexOf(x).ToString)
    
    Next
    
    End If
    

    Tuesday, November 10, 2009 8:08 AM
  • It should be like this

     

    foreach (ListBoxItem listItem in listBox1.Items)
        {
           if (listItem.Selected == True)
           {
              //listItem.Value contains the value of the selected item
              //listItem.Text is the text displayed in the listbox of the selected item
           }
        }

    Monday, April 19, 2010 9:36 AM
  • Does this only work in v3.5 and above in Windows apps?  I can't get this to work on a web page.  I have a v3.5 ASP.NET page and I have had to make reference to PresentationCore, PresentationFramework and WindowsBase and I am still getting strange errors....

    Error Message => The event 'System.Windows.Controls.ListBoxItem.Selected' can only appear on the left hand side of += or -=

     

    Monday, May 24, 2010 9:49 PM
  • Thanks very much. I've been looking for this for hours now. Glad I found your post and this solution works really well for be because my ListBox derive its' data from a dataset.

     

    thanks again!

    Tuesday, June 28, 2011 9:54 AM
  • thanks man...this is really good n correct
    Friday, July 22, 2011 1:54 PM
  • Thanks, BeefyDog. Your solution worked perfectly. Here is BeefyDog's solution rewritten in C#: 

     

     

        string retval = "";

                try

                {

                    foreach (DataRowView drv in lbx.SelectedItems)

                    {

                        retval += drv.Row[2].ToString().Replace(" ", "").ToUpper() + ","; // index in '[]' will vary

                    }

                }

                catch (IndexOutOfRangeException ex)

                {

                    MessageBox.Show("Error occured: " + ex.Message);

                }

     

     


    Tuesday, November 15, 2011 6:06 PM
  • Here's an alternative
    foreach (int index in ListBox.GetSelectedIndices())
    {
         String itemValue = ListBox.Items[index].Value;
         //Process(itemValue);
    }
    


    Saturday, December 03, 2011 12:56 AM
  • I used VS 2010,asp.net,This solution works for me!
    Thanks so much,K.wsanstos15.


    Friday, December 30, 2011 4:23 AM
  • Thanks a loott.This code works perfectlty:)


    Rahul

    Tuesday, February 14, 2012 10:06 AM
  • I spent hours and hours trying to find this(not wording google correctly, I blame not having enough coffee) and works perfect.

    Thanks for your help,

    William.


    William

    Monday, February 11, 2013 7:12 PM
  • Perfect. I couldn't get my winform listbox selected items values.

    Your solution works fine for me. Thanks a lot.

    G.M. from France

    Sunday, April 06, 2014 11:37 PM