tags:

views:

680

answers:

4

I have a listbox of names, I want to click one of the names so that it is highlighted and then click a button that runs some code for the selected item. How do I call this selected item?

    private void btnEcho_Click(object sender, EventArgs e)
    {
         listbox1.SelectedItem......
    }

Many thanks

A: 
String s = listbox1.SelectedItem.Value.ToString();

Don't forget to do a null check, because this will throw an error if your list is empty or if no value is selected.

Elie
if this is a web project, you can leave off the ToString() as the Value property is a string already.
Michael Haren
He didn't specify, but you are correct, of course.
Elie
ah, it looks like the "listbox" should have clued me in that it's not an aspnet project. Sorry
Michael Haren
A: 

You're question is not clearly to me.

Example, you have a listbox of three items: A, B and C. You have, as you do with your example, a click-event. In that click-event you can use the switch-statement to handle some code for each item:

switch (listbox1.SelectedItem)
{
  case "A":
       // Code when select A
       break;
  case "B":
       // Code when select B
       break;
  ... (and so on).
}

Code is an example and not tested. See switch for more information.

+1  A: 

The listbox isn't very intuitive because it contains objects instead of something like ListItem, but if you just want the text you can do this:

string selectedText = listbox1.SelectedItem.ToString();
jhunter
Don't forget the null check. What if nothing is selected? Or your list contains no items?
Elie
A: 

Listbox1.SelectedItem gets the actual selected item. You can then further call from SelectedItem to get other properties/methods such as SelectedItem.Text or SelectedItem.Value

If you wanted to make it all happen upon selection from the listbox (instead of pressing a button), you could just add a SelectedIndexChanged event for Listbox1 (and in ASP.NET make sure that AutoPostBack is set to TRUE)

TheTXI