C # How to run code for selected item in list?

I have a list 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 can I name this selected item?

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

      

Many thanks

+1


source to share


5 answers


The list is not very intuitive because it contains objects instead of something like ListItem, but if you just want text, you can do this:



string selectedText = listbox1.SelectedItem.ToString();

      

+1


source


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

      



Remember to do a null check, because it will throw an error if your list is empty or if no value is selected.

0


source


Listbox1.SelectedItem

gets the actual selected item. Then you can call from SelectedItem to get other properties / methods like SelectedItem.Text

orSelectedItem.Value

If you want all of this to happen when you select from the list (instead of clicking a button), you can simply add an event SelectedIndexChanged

for Listbox1 (and in ASP.NET, make sure the parameter is AutoPostBack

set to TRUE).

0


source


string str = listbox1.SelectedValue.ToString();

      

here you have what value (name).

if(str == null || str == string.empty) return;

      

etc. you can do what you want; Good luck

0


source


You are not clear to me.

For example, you have a list of three elements: A, B, and C. You have, like your example, a click event. In this click event, you can use a 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).
}

      

The code is example and untested. See Switch section for more information.

-1


source







All Articles