How to get multiple selected values and items from listbox ?

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

  • Monday, November 21, 2005 9:37 AM
     
     

    Hi people,

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

All Replies

  • Monday, November 21, 2005 10:17 AM
     
     
    You can use the SelectedItems property. It will give you a collection of all selected items.
  • Monday, November 21, 2005 3:46 PM
     
     
     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 6:34 PM
     
     
    You can do a for or a ForEach. And SelectedItem[index] get you the item in the index.
  • Monday, November 21, 2005 6:42 PM
     
     Answered
    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);
                }
            }

     

  • Tuesday, November 22, 2005 2:14 AM
     
     
     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 8:32 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
           }
        }


     
  • Monday, August 14, 2006 10:43 PM
     
     
    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!!!

  • Tuesday, June 12, 2007 1:20 PM
     
     
    Hallo, i've got the same problem and i work with .net Framework 1.1, how can i do?
  • Tuesday, June 12, 2007 2:35 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?

  • Wednesday, June 13, 2007 7:28 AM
     
     

    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.

     

     

     

     

  • Thursday, June 14, 2007 8:01 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

     

  • Sunday, June 24, 2007 12:38 PM
     
     

    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?

     

     

  • Monday, June 25, 2007 8:30 AM
     
     
     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 11:35 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 3:34 PM
     
     
    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.


  • Tuesday, June 26, 2007 9:04 AM
     
     
    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?
  • Wednesday, June 27, 2007 12:54 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, July 25, 2007 6:48 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 7:05 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

     

  • Monday, September 15, 2008 8:46 AM
     
     

    Oye Thank You Dost,

     

    Its working fine.

     

     

    Anil Chauhan

     

  • Thursday, January 22, 2009 5:57 AM
     
     Proposed Has Code
    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
    •  
  • Friday, March 13, 2009 4:35 AM
     
     
    It works, thank you very much, I spent more time for this problem, thanks!!!
  • Saturday, September 05, 2009 5:08 AM
     
     
    Man this realy works
    there any way to know which are the columns in dataview?
    In addition to querying the database?
  • Tuesday, November 10, 2009 8:08 AM
     
      Has Code

     

     

    ' 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
    

  • Monday, April 19, 2010 9:36 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, May 24, 2010 9:49 PM
     
     

    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 -=

     

  • Tuesday, June 28, 2011 9:54 AM
     
     

    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!

  • Friday, July 22, 2011 1:54 PM
     
     
    thanks man...this is really good n correct
  • Tuesday, November 15, 2011 6:06 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);

                }

     

     


  • Saturday, December 03, 2011 12:56 AM
     
     Proposed Has Code
    Here's an alternative
    foreach (int index in ListBox.GetSelectedIndices())
    {
         String itemValue = ListBox.Items[index].Value;
         //Process(itemValue);
    }
    


    • Proposed As Answer by SnapperThailand Friday, December 30, 2011 4:21 AM
    •  
  • Friday, December 30, 2011 4:23 AM
     
     

    I used VS 2010,asp.net,This solution works for me!
    Thanks so much,K.wsanstos15.


  • Tuesday, February 14, 2012 10:06 AM
     
     

    Thanks a loott.This code works perfectlty:)


    Rahul

  • Monday, February 11, 2013 7:12 PM
     
     

    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