简体   繁体   English

如何获取列表框中所选项目的编号(C#)

[英]How do I get the number of the item selected in a listbox (C#)

I'm trying to get the integer value of The number selected of the item. 我正在尝试获取该项目所选数字的整数值。

For example 例如

[Sample List Box]
Beans
Rice
Can
Potatoe
[/Sample List Box]

Rice is number 2 饭是第二名

How can I do that in C#? 如何在C#中做到这一点?

Do you mean the index of the item? 您是指商品的索引吗?

MyListBox.SelectedIndex

should give it to you. 应该给你。 But Rice in that case is index no. 但是在这种情况下,赖斯是第一个指数。 1, not 2. 1,不是2。

Add one to index position of the selected list item to get a one-based number position. 在所选列表项的索引位置添加一个,以获取一个基于数字的位置。

listBox1.SelectedIndex + 1;

If zero is returned after this math, (index is -1) you know nothing is selected. 如果此数学运算后返回零(索引为-1),则说明您未选择任何内容。

Well, I am not sure whether you are talking web or windows. 好吧,我不确定您是在谈论网络还是在谈论Windows。 In the case of Windows Forms or WPF, you can simply use the SelectedIndex property on the ListBox control. 对于Windows窗体或WPF,您可以简单地使用ListBox控件上的SelectedIndex属性。 In the case of ASP.NET Web Forms, you can handle the SelectedIndexChanged event on the server side, and get the SelectedIndex property. 对于ASP.NET Web窗体,可以在服务器端处理SelectedIndexChanged事件,并获取SelectedIndex属性。

If you are using ASP.NET MVC, the view is generally simple HTML, and there is no control on the server side to represent it. 如果使用的是ASP.NET MVC,则视图通常是简单的HTML,并且服务器端没有控件来表示它。 You'll probably need to roll you're own solution if your using MVC. 如果您使用的是MVC,则可能需要推出自己的解决方案。

You want the selected index? 您要选择索引吗?

listBox1.SelectedIndex

or the selected item? 或所选项目?

listBox1.SelectedItem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM