Loop the loop...

G

Guest

I have an error on one of my loops and am not completely sure why I keep
getting the following error message!

Insertion index was out of range. Must be non-negative and less than or
equal to size. Parameter name: index

Would appritiate any input... Thanks


...CODE
Private Sub PopulateDDLNoMobAccounts()
'assuming you have a button named ForLoop
Dim i As Integer
For i = 1 To 10
v_intNoMobilePhoneNumbers.Items.Insert(i, "i")
v_intNoMobilePhoneNumbers.Items.FindByText("i").Value = i
Next i
v_intNoMobilePhoneNumbers.DataBind()
v_intNoMobilePhoneNumbers.Items.Insert(0, "Select One")
v_intNoMobilePhoneNumbers.Items.FindByText("Select One").Value = 0
'insert don't create a value, but we need a value during defaults
v_intNoMobilePhoneNumbers.SelectedIndex = 0
End Sub
 
I

Iain Norman

I have an error on one of my loops and am not completely sure why I keep
getting the following error message!

Insertion index was out of range. Must be non-negative and less than or
equal to size. Parameter name: index

Would appritiate any input... Thanks


..CODE
Private Sub PopulateDDLNoMobAccounts()
'assuming you have a button named ForLoop
Dim i As Integer
For i = 1 To 10
v_intNoMobilePhoneNumbers.Items.Insert(i, "i")
v_intNoMobilePhoneNumbers.Items.FindByText("i").Value = i
Next i
v_intNoMobilePhoneNumbers.DataBind()
v_intNoMobilePhoneNumbers.Items.Insert(0, "Select One")
v_intNoMobilePhoneNumbers.Items.FindByText("Select One").Value = 0
'insert don't create a value, but we need a value during defaults
v_intNoMobilePhoneNumbers.SelectedIndex = 0
End Sub
Is it zero indexed?

I
 
K

Karl Seguin

Tim:
you are trying to insert in position 1 before inserting anything in position
0, try this for simpler, cleaner code:

For i As Integer = 1 To 10
v_intNoMobilePhoneNumbers.Items.Add(New ListItem(i.ToString(),
i.ToString()))
Next i
v_intNoMobilePhoneNumbers.Items.Insert(0, New ListItem("Select One", "0"))
v_intNoMobilePhoneNumbers.SelectedIndex = 0

(a) notice that I don't use insert...insert is when you want to put
something in a specific position, at first we just want to add the items
(b) note that I still use insert to add the "Select One" as the very first
item
(c) I got rid of the DataBind() this does nothing unless you are
databinding except eat up cycles
(d) I add/insert new ListItems which allows me to specify both the text and
the value in a single line
(e) I turned on Option Strict which means I can't just assign i to something
which expects a string - I must ToString() it (always use option strict)


Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top