Getting value of selected item in list box as string

Amrit Sharma picture Amrit Sharma · Feb 21, 2013 · Viewed 248.6k times · Source

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

Answer

Thomas Levesque picture Thomas Levesque · Feb 21, 2013

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

string text = listBox1.GetItemText(listBox1.SelectedItem);