mahesh
mahesh

Reputation: 1390

Listbox Error On Selection Index

I have a listbox control on winform and same is Single Items SelectionMode OR One Items Selection Mode. I am trying to scroll it from form_KeyDown Event as below

if ((Keys)e.KeyCode == Keys.Down)
{
     if (listBox2.Items.Count >= listBox2.SelectedIndex) 
     {
           listBox2.SelectedIndex++;

     }

 }

But it’s throw an error like “ArgumentOutOfRangeException was unhandled” Invalid argument of value =23 is not valid for selection index.

How to get ridoff?

Upvotes: 0

Views: 731

Answers (3)

smoth190
smoth190

Reputation: 438

According to MSDN's documentation on ListBox.SelectedIndex:

A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.

So, I believe you need to change

if (listBox2.Items.Count >= listBox2.SelectedIndex)

to

if (listBox2.Items.Count-1 > listBox2.SelectedIndex)

Please vote Marco's answer as correct, as he pointed this out to me!

Because if there are 23 items in the listbox, item 23 is actually item 22, item 1 is actually item 0, etc. etc.

Upvotes: 1

Wayne Phipps
Wayne Phipps

Reputation: 2069

ListBox.SelectedIndex is a zero based array IE the first item will be 0 in the index whereas the Items.Count will always return a value starting at 1.

Please see the following for further information: http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindex.aspx

Kind Regards, Wayne

Upvotes: 1

Marco
Marco

Reputation: 57593

Try this:

if ((Keys)e.KeyCode == Keys.Down)
{
     if ((listBox2.Items.Count-1) > listBox2.SelectedIndex) 
     {
           listBox2.SelectedIndex++;

     }

 }

Remember that if you have 23 items, SelectedIndex goes from 0 to 22...

Upvotes: 2

Related Questions