abaldwin99
abaldwin99

Reputation: 913

Code getting skipped after 'For' loop

I'm seeing some strange behavior during my form load event. Everything works as expected until I run a For loop. Any code below the Next line won't fire. I get no error the form just loads like every things good but it ignores those lines. I have placed a msgbox("test") above and below the loop to confirm this behavior.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'Do some form loading stuff

    msgbox("test1") 'This will Fire

    For i = 0 To DataGridView1.Columns.Count
        DataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
    Next

    msgbox("test2") 'This wont fire

End Sub

I could fix this by just putting the loop at the bottom of the form load but it bugs to me to not understand why this is happening.

EDIT: After further testing I've found out that if I just run the FOR loop without changing the sort mode then the test2 messagebox will fire. If I comment out the sortmode line everything works fine. Something about setting the sort mode in a loop is preventing the rest of the code from running.

P.S. If anyone knows of a better way to make a databound datagridview with extra columns not sort-able i'm all ears.

Upvotes: 0

Views: 99

Answers (2)

Jamby
Jamby

Reputation: 1917

There's an error in your code: you can't enumerate untill DataGridView1.Columns.Count Fix it like this:

For i = 0 To DataGridView1.Columns.Count -1
    DataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
Next

By the way, you don't see the MsgBox because DataGridView1.Columns(i) is going to raise an exception, but this exception will be ignored if it's in the Load method.

Upvotes: 2

Steve
Steve

Reputation: 216343

The problem is the loop that executes once too often

Arrays in NET starts at index zero and the maximum index is the length of the array minus one

For i = 0 To DataGridView1.Columns.Count - 1
    DataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
Next

Your loop causes an exception that is probably trapped in the caller code and silently suppressed or, being in the load method and if you execute this code inside VS debugger, it is simply not catched for a well know problem with the load event in 64bit code with a debugger attached.

Upvotes: 4

Related Questions