Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of selected item in list box as string

I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.

DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem)); 

Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.

How can i retrive the value of selected item as string?

I am adding items to listbox from combo box which in turn loads the items from the database.

 listBox1.Items.Add(comboBox2.Text); 

enter image description here

Anybody has answer for this..

like image 745
Amrit Sharma Avatar asked Feb 21 '13 13:02

Amrit Sharma


People also ask

How do you retrieve the selected item in a ListBox?

To retrieve a collection containing all selected items in a multiple-selection ListBox, use the SelectedItems property. If you want to obtain the index position of the currently selected item in the ListBox, use the SelectedIndex property.

How get multiple values from ListBox in VB net?

You can use ListBox. SelectedItems . "System.

Which method is used to add an item from a list box?

To insert an item into the list box at a specific position, use the Insert method. To add a set of items to the list box in a single operation, use the AddRange method.

How does ListBox work in C#?

In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events.


2 Answers

If you want to retrieve the display text of the item, use the GetItemText method:

string text = listBox1.GetItemText(listBox1.SelectedItem); 
like image 176
Thomas Levesque Avatar answered Sep 25 '22 17:09

Thomas Levesque


If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)     {          label1.Text  = listBox1.SelectedItem.ToString();     } 
like image 23
Pir Fahim Shah Avatar answered Sep 23 '22 17:09

Pir Fahim Shah