简体   繁体   English

如何获取列表框选定的项目值

[英]How to get listbox selected item value

I am working with C# .NET 4.0 我正在使用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 在我的设计器中,我将file_name指定为DisplayMember,将file_id指定为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". 但它返回的只是"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? 如何从列表框中的单个选定项获取ValueMember值?

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. columnName替换为要从中获取数据的列的名称,该列将与数据源中的列对应。

Also watch out for nulls if there's no selected item. 如果没有选定项目,请注意空值。

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 选择ListBox控件
  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. 如果我取消选择该框,我会得到与您描述的完全相同的行为。

在此输入图像描述

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

You may need to set the DataValueField of the listbox. 您可能需要设置列表框的DataValueField。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM