Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get listbox selected item value

Tags:

c#

listbox

I am working with C# .NET 4.0

I am trying to get the value of a single selected item in a listbox.

This is how I populate the control:

this.files_lb.DataSource = DataTable object

In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue

After selecting an item in the listbox, I tried the following to get the value:

this.files_lb.SelectedValue.ToString()

But all it returns is "System.Data.DataRowView".

At this link : Getting value of selected item in list box as string

someone suggested -

String SelectedItem = listBox1.SelectedItem.Value

However, 'Value' is not an option when I try this.

How can I get the ValueMember value from a single selected item in a listbox?

like image 502
Lee Loftiss Avatar asked Feb 12 '14 02:02

Lee Loftiss


2 Answers

var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();

Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.

Also watch out for nulls if there's no selected item.

like image 102
Jon Barker Avatar answered Sep 19 '22 20:09

Jon Barker


It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:

private void button1_Click(object sender, EventArgs e)
    {
        string selected = listBox1.GetItemText(listBox1.SelectedValue);
        MessageBox.Show(selected);
    }

And the result:

enter image description here


Edit

It looks like your issue may be from not setting a property on the control:

enter image description here

  1. Select the ListBox control
  2. Click the little arrow to show the binding / items options
  3. Select Use Data Bound Items

If I deselect that box, I get the exact same behavior you are describing.

like image 30
Austin T French Avatar answered Sep 20 '22 20:09

Austin T French