Question

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#?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Well, I am not sure whether you are talking web or windows. In the case of Windows Forms or WPF, you can simply use the SelectedIndex property on the ListBox control. In the case of ASP.NET Web Forms, you can handle the SelectedIndexChanged event on the server side, and get the SelectedIndex property.

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. You'll probably need to roll you're own solution if your using MVC.

You want the selected index?

listBox1.SelectedIndex

or the selected item?

listBox1.SelectedItem
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top