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

الإجابات

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

     

    19/شوال/1426 06:42 م

جميع الردود

  • You can use the SelectedItems property. It will give you a collection of all selected items.
    19/شوال/1426 10:17 ص
  •  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 ?
    19/شوال/1426 03:46 م
  • You can do a for or a ForEach. And SelectedItem[index] get you the item in the index.
    19/شوال/1426 06:34 م
  • 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);
                }
            }

     

    19/شوال/1426 06:42 م
  •  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#
    20/شوال/1426 02:14 ص
  • 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
           }
        }


     
    20/شوال/1426 08:32 ص
  • 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!!!

    • تم الاقتراح كإجابة بواسطة Roelof Kallenkoot 29/جمادى الثانية/1435 09:44 ص
    20/رجب/1427 10:43 م
  • Hallo, i've got the same problem and i work with .net Framework 1.1, how can i do?
    26/جمادى الأولى/1428 01:20 م
  •  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?

    26/جمادى الأولى/1428 02:35 م
  • 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.

     

     

     

     

    27/جمادى الأولى/1428 07:28 ص
  • 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

     

    28/جمادى الأولى/1428 08:01 ص
  • 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?

     

     

    09/جمادى الثانية/1428 12:38 م
  •  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.

    10/جمادى الثانية/1428 08:30 ص
  •  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?!

    10/جمادى الثانية/1428 11:35 ص
  • 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.


    10/جمادى الثانية/1428 03:34 م
  • 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?
    11/جمادى الثانية/1428 09:04 ص
  • 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.
    12/جمادى الثانية/1428 12:54 ص
  • 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.

    11/رجب/1428 06:48 ص
  • 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

     

    11/رجب/1428 07:05 ص
  • Oye Thank You Dost,

     

    Its working fine.

     

     

    Anil Chauhan

     

    15/رمضان/1429 08:46 ص
  • 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 

    • تم الاقتراح كإجابة بواسطة h0us3 15/رمضان/1430 05:06 ص
    25/محرم/1430 05:57 ص
  • It works, thank you very much, I spent more time for this problem, thanks!!!
    16/ربيع الأول/1430 04:35 ص
  • Man this realy works
    there any way to know which are the columns in dataview?
    In addition to querying the database?
    15/رمضان/1430 05:08 ص
  •  

     

    ' 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
    

    22/ذو القعدة/1430 08:08 ص
  • 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
           }
        }

    05/جمادى الأولى/1431 09:36 ص
  • 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 -=

     

    10/جمادى الثانية/1431 09:49 م
  • 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!

    26/رجب/1432 09:54 ص
  • thanks man...this is really good n correct
    21/شعبان/1432 01:54 م
  • 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);

                }

     

     


    • تم التحرير بواسطة pianocomposer 19/ذو الحجة/1432 07:23 م
    19/ذو الحجة/1432 06:06 م
  • Here's an alternative
    foreach (int index in ListBox.GetSelectedIndices())
    {
         String itemValue = ListBox.Items[index].Value;
         //Process(itemValue);
    }
    


    • تم الاقتراح كإجابة بواسطة SnapperThailand 05/صفر/1433 04:21 ص
    08/محرم/1433 12:56 ص
  • I used VS 2010,asp.net,This solution works for me!
    Thanks so much,K.wsanstos15.


    05/صفر/1433 04:23 ص
  • Thanks a loott.This code works perfectlty:)


    Rahul

    22/ربيع الأول/1433 10:06 ص
  • 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

    01/ربيع الثاني/1434 07:12 م
  • Perfect. I couldn't get my winform listbox selected items values.

    Your solution works fine for me. Thanks a lot.

    G.M. from France

    06/جمادى الثانية/1435 11:37 م
  • 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!!!

    Best answer if you're using a Databound ListBox.
    29/جمادى الثانية/1435 09:52 ص