How to get listbox selected item value

2020-06-22 18:46发布

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?

标签: c# listbox
4条回答
Anthone
2楼-- · 2020-06-22 19:22

enter image description here

var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{ 
     MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}
查看更多
狗以群分
3楼-- · 2020-06-22 19:24

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.

查看更多
Ridiculous、
4楼-- · 2020-06-22 19:29

You may need to set the DataValueField of the listbox.

NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new 
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
            NewEmployeesLB.DataTextField = "Text";
            NewEmployeesLB.DataValueField = "Value";
            NewEmployeesLB.DataBind();
查看更多
小情绪 Triste *
5楼-- · 2020-06-22 19:41

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.

查看更多
登录 后发表回答