How to get listbox selected item value

瘦欲@ 提交于 2019-12-03 15:51:42

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.

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.

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

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