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
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).
source to share
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.
source to share