How to get listbox selected item value

左心房为你撑大大i 提交于 2019-12-09 13:05:19

问题


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?


回答1:


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.




回答2:


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:


Edit

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

  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.




回答3:


var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{ 
     MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}



回答4:


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();


来源:https://stackoverflow.com/questions/21717444/how-to-get-listbox-selected-item-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!