[英]C# How do I run some code for the selected item in a listbox?
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 非常感谢
列表框不是很直观,因为它包含对象而不是诸如ListItem之类的东西,但是如果您只想要文本,则可以执行以下操作:
string selectedText = listbox1.SelectedItem.ToString();
string str = listbox1.SelectedValue.ToString();
here you have the what value(name) selected. 在这里,您选择了什么值(名称)。
if(str == null || str == string.empty) return;
and so on. 等等。 you can do whatever you want; 你想做什么,就可以做什么; goodluck 祝好运
String s = listbox1.SelectedItem.Value.ToString();
不要忘记进行空检查,因为如果您的列表为空或未选择任何值,这将引发错误。
Listbox1.SelectedItem
gets the actual selected item. Listbox1.SelectedItem
获取实际的选定项目。 You can then further call from SelectedItem to get other properties/methods such as SelectedItem.Text
or SelectedItem.Value
然后,您可以从SelectedItem进一步调用以获取其他属性/方法,例如SelectedItem.Text
或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) 如果要使所有操作都在列表框中进行选择(而不是按按钮),则可以为Listbox1添加SelectedIndexChanged
事件(并在ASP.NET中确保将AutoPostBack
设置为TRUE)。
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. 例如,您有一个包含三个项目的列表框:A,B和C。与示例一样,您拥有一个点击事件。 In that click-event you can use the switch-statement to handle some code for each item: 在该单击事件中,您可以使用switch语句为每个项目处理一些代码:
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. 请参阅开关以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.