none
value from a listbox in a windowsforms

    Question

  • Hello expert;

    I have spent time searching for this. I need to get the value for a selected item from the listbox not the item. Please see my code below.

    foreach ( var item in listBox1.SelectedItems)
    {

    //this get my item

    listBox1.GetItemText(item) 

    // I need help to get the value, can you please help me with the code.

    }

    Tuesday, March 14, 2017 8:35 PM

Answers

  • Hi,

    how do you have assigned the *values* to the listbox? Do you have a different display text than the value, eg by using Display and ValueMembers?

    http://stackoverflow.com/questions/22487326/getting-valuemember-from-selected-item-in-a-listbox-with-c-sharp

    Regards,

      Thorsten

    • Marked as answer by olybobo Wednesday, March 15, 2017 2:40 PM
    Wednesday, March 15, 2017 4:26 AM

All replies

  • Hi olybobo,

    In advance, sorry if I misunderstand your intention.

    You can get the selected value/text in listBox:
    your item = listBox1.Text; 
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    	txt_item.Text = listBox1.Text;
    }
    

    Regards,
    Ashidacchi
    Wednesday, March 15, 2017 12:45 AM
  • Hi Ashidacchi;

    That gets the text not the value. For instance, I have a listbox

    the user see text grape but the value is 3 

                       text apple but the value is 2 

                       text banana but the value is 1

    and so on. I want the user to be able to pick grape but I want to pass value 3 to my function.

    Wednesday, March 15, 2017 1:14 AM
  • Hi olybobo,

    Thanks.
    I got noticed you meant "value" as index of listBox.
    An index of listBox begins from zero, instead of 1.
    So, you can add 1 to a SelectedIndex of listBox.


    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    	txt_item.Text = listBox1.Text;
    	txt_index.Text = (listBox1.SelectedIndex + 1).ToString();
    }

    Regards,
    Ashidacchi
    Wednesday, March 15, 2017 2:03 AM
  • If you have the object and you want to convert it to an index, you cane use the IndexOf method of the item list.

             foreach (object item in listBox1.SelectedItems)
             {
                int index = listBox1.Items.IndexOf(item);  // zero-based, as Ashidacchi points out.
             }

    Wednesday, March 15, 2017 3:57 AM
  • Hi,

    how do you have assigned the *values* to the listbox? Do you have a different display text than the value, eg by using Display and ValueMembers?

    http://stackoverflow.com/questions/22487326/getting-valuemember-from-selected-item-in-a-listbox-with-c-sharp

    Regards,

      Thorsten

    • Marked as answer by olybobo Wednesday, March 15, 2017 2:40 PM
    Wednesday, March 15, 2017 4:26 AM
  • HI Thorsten;

    Yes I do. My display and valuemember are different

    Wednesday, March 15, 2017 2:14 PM