Jarred Sumner
Jarred Sumner

Reputation: 1863

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

Upvotes: 0

Views: 306

Answers (4)

John K
John K

Reputation: 28917

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.

Upvotes: 1

user1921
user1921

Reputation:

You want the selected index?

listBox1.SelectedIndex

or the selected item?

listBox1.SelectedItem

Upvotes: 0

Ralph Lavelle
Ralph Lavelle

Reputation: 5769

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.

Upvotes: 2

jrista
jrista

Reputation: 33010

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.

Upvotes: 0

Related Questions