Results 1 to 12 of 12

Thread: Simple for to loop

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2016
    Location
    South Africa
    Posts
    142

    Simple for to loop

    Can any please tell me what I am missing in this very simple for to loop ?


    Code:
     
    
            For index As Integer = 15 To 21 Step 1
    
    
                MsgBox("This is the loop no : " & index.ToString)
             
    
                'If index = 22 Then
                '    MsgBox("This is the loop 22 : " & index.ToString)
                '    Exit For
                'End If
    
            Next

    When I run the code it increments to 21 and then start from 15 again. It never exits the loop. I have also tried if endif exit for(commented out ).

    Clearing I am missing something very basic, but I'm missing it.

    Regards

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Simple for to loop

    There is nothing in that code that would cause that to happen. Either there's something else going on that you haven't shown us, e.g. it's in a Do loop, or something on your system is broken. I suggest that you step through the code in the debugger with a watch on the index variable and see exactly what happens. You should also test similar code in a separate code file and a separate project and things like that.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Nov 2016
    Location
    South Africa
    Posts
    142

    Re: Simple for to loop

    Thank you for replying.

    You are right, when I use the code in a new project it executes as expected.

    I am using the code within a datagridview's RowStateChanged event as I would like to make calculations every time a cell value is changed.

    I have already accomplished this with a sub procedure, but now would like to do it with a function.
    The sub executes as expected using the sub, but I would like to increase the cell value and result automatically.
    The sub and function below.
    Code:
     Private Sub search()
            tot = 0
            For Each r As DataGridViewRow In SkeduleringDataGridView.Rows.Cast(Of DataGridViewRow)().Where(Function(row) row.Visible = True)
    
                If IsNumeric(r.Cells(15).Value) Then
                    tot += Val(r.Cells(15).Value)
                End If
    
            Next
    
    
            TOTALMA1.Text = tot.ToString()
        End Sub
    
    
        Private Function somvirdag(ByVal r As Integer) As Decimal
    
            tot = 0
            For Each ry As DataGridViewRow In SkeduleringDataGridView.Rows.Cast(Of DataGridViewRow)().Where(Function(row) row.Visible = True)
    
                If IsNumeric(ry.Cells(r).Value) Then
                    tot += Val(ry.Cells(r).Value)
                End If
    
            Next
            Return tot
        End Function

    Regards

  4. #4
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,630

    Re: Simple for to loop

    Quote Originally Posted by GideonE View Post
    Thank you for replying.

    You are right, when I use the code in a new project it executes as expected.

    I am using the code within a datagridview's RowStateChanged event as I would like to make calculations every time a cell value is changed.

    I have already accomplished this with a sub procedure, but now would like to do it with a function.
    The sub executes as expected using the sub, but I would like to increase the cell value and result automatically.
    The sub and function below.
    Code:
     Private Sub search()
            tot = 0
            For Each r As DataGridViewRow In SkeduleringDataGridView.Rows.Cast(Of DataGridViewRow)().Where(Function(row) row.Visible = True)
    
                If IsNumeric(r.Cells(15).Value) Then
                    tot += Val(r.Cells(15).Value)
                End If
    
            Next
    
    
            TOTALMA1.Text = tot.ToString()
        End Sub
    
    
        Private Function somvirdag(ByVal r As Integer) As Decimal
    
            tot = 0
            For Each ry As DataGridViewRow In SkeduleringDataGridView.Rows.Cast(Of DataGridViewRow)().Where(Function(row) row.Visible = True)
    
                If IsNumeric(ry.Cells(r).Value) Then
                    tot += Val(ry.Cells(r).Value)
                End If
    
            Next
            Return tot
        End Function

    Regards
    See the two bolded statements above and think about what you are saying and you should see why the behavior you are seeing is happening.

  5. #5
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: Simple for to loop

    Hi Gideon,

    Are you asking for a way to call the function from the RowStateChanged event?

  6. #6
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,630

    Re: Simple for to loop

    Quote Originally Posted by schoemr View Post
    Hi Gideon,

    Are you asking for a way to call the function from the RowStateChanged event?
    The OP hasn't provided enough code to demonstrate the exact issue, but based on what they have posted and their description of what is happening and what they are trying to accomplish, this is almost certainly what is happening:

    Whenever a cell value is changed, they run some "cell value was changed" code
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    That code changes a cell value, so "cell value was changed code" gets run
    ...

  7. #7
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: Simple for to loop

    O okay, seems like infinite loop..

  8. #8
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,630

    Re: Simple for to loop

    Quote Originally Posted by schoemr View Post
    O okay, seems like infinite loop..
    I would describe it as "infinite implicit recursion". The method isn't calling itself directly (explicit recursion), but rather is making a change that triggers the event that calls the method again, repeat.

    Again, just best guess speculation based on the lack of all contextual code from the OP.

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Simple for to loop

    Yeah, that sounds right. The one issue I have with it is that it should have crashed with an Stack Overflow exception. If there really were MessageBoxes in the actual method, as was shown in the initial post, that would explain why the exception never happened. He just never let it run long enough. Without something like a messagebox, it should have overflowed the stack.

    In any case, looking at the Stack Trace should show a repeating pattern, with the same method(s) being called over and over and over.

    One other point I'd like to add is that Val() is quite risky, in this case. That function is useful at times, but it has a problem that can really bite a person. It starts converting a string from the leftmost character until it either hits a character it can't turn into a number, or runs out of characters, then it returns whatever it has. If it runs out of characters, then you get what you want. If it hits a character it can't convert, then you will get...something, but not what you want. For example:

    Val("1234") = 1234
    Val("1.234") = 1.234
    Val("1,234") = 1
    Val("$1234") = 0

    Those last two tend to trip people up.
    My usual boring signature: Nothing

  10. #10
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,630

    Re: Simple for to loop

    Quote Originally Posted by Shaggy Hiker View Post
    Yeah, that sounds right. The one issue I have with it is that it should have crashed with an Stack Overflow exception. If there really were MessageBoxes in the actual method, as was shown in the initial post, that would explain why the exception never happened. He just never let it run long enough. Without something like a messagebox, it should have overflowed the stack.
    It probably did throw Stack Overflow exceptions originally, and I would assume that the messageboxes were added by the OP as a way to try to track down why, and that's as far as they got before posting.

  11. #11
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Simple for to loop

    Quote Originally Posted by GideonE View Post
    I am using the code within a datagridview's RowStateChanged event as I would like to make calculations every time a cell value is changed.
    This way of doing things had it's time when dinosaurs roamed the Earth. Fiddling around with events like this is bound to cause issues eventually due to how messy it is. The way we handle this kind of thing in the modern day is through data binding which thankfully, even WinForms supports. It tends to result in much cleaner designs that are easier to reason about.

    Here is an example:-
    Code:
    Imports System.ComponentModel
    Imports System.Runtime.CompilerServices
    
    Public Class Form1
    
        Private _data As BindingList(Of Person)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            _data = New BindingList(Of Person)(GenerateSampleData())
    
            DataGridView1.DataSource = _data
        End Sub
        Public Function GenerateSampleData() As Person()
            Dim random As New Random()
            Dim people(9) As Person
    
            Dim firstNames() As String = {"John", "Jane", "Michael", "Michelle", "David", "Amy", "Robert", "Emily", "James", "Mary"}
            Dim lastNames() As String = {"Smith", "Johnson", "Brown", "Jones", "Garcia", "Davis", "Wilson", "Lee", "Harris", "Clark"}
    
            For i As Integer = 0 To 9
                Dim firstName As String = firstNames(random.Next(firstNames.Length))
                Dim lastName As String = lastNames(random.Next(lastNames.Length))
                Dim birthDate As Date = Date.Now.AddYears(-random.Next(20, 60)).AddDays(-random.Next(365))
                Dim age As Integer = Date.Now.Year - birthDate.Year
    
                people(i) = New Person With {.FirstName = firstName, .LastName = lastName, .BirthDate = birthDate}
            Next
    
            Return people
        End Function
    
        Public Class Person
            Implements INotifyPropertyChanged
    
            Private _firstName As String
            Private _lastName As String
            Private _birthDate As Date
    
            Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    
            Public Property FirstName As String
                Get
                    Return _firstName
                End Get
                Set(value As String)
                    _firstName = value
                    OnPropertyChanged()
                End Set
            End Property
    
            Public Property LastName As String
                Get
                    Return _lastName
                End Get
                Set(value As String)
                    _lastName = value
                    OnPropertyChanged()
                End Set
            End Property
    
            Public Property BirthDate As Date
                Get
                    Return _birthDate
                End Get
                Set(value As Date)
                    _birthDate = value
                    OnPropertyChanged()
                    OnPropertyChanged(NameOf(Age))
                End Set
            End Property
            Public ReadOnly Property Age As Integer
                Get
                    Return DateTime.Today.Year - _birthDate.Year
                End Get
            End Property
    
            Private Sub OnPropertyChanged(<CallerMemberName> Optional ByVal propertyName As String = "")
                RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
            End Sub
        End Class
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            'Make each person 10 years older by
            'changing the birth day. Notice that
            'this automatically updates the age in the
            'DataGridView
            For Each p In _data
                p.BirthDate = p.BirthDate.AddYears(-10)
            Next
        End Sub
    End Class
    To test, just create a new WinForms project and put a Button and DataGridView on Form1.

    The sample shows information of 10 people in a DataGridView and clicking the button ages each person by 10 years. Each person's information is stored in a class. Take notice of the Age property. It is read-only and calculated by using the person's birth day. Clicking the button moves back their birthday 10 years and you will see it also changes the Age in the DataGridView to reflect the change in birthday. No need to mess around with events like RowStateChanged and all that. You could even change the birth day by typing it directly in the DataGridView itself and the Age will change to reflect what you put in.

    The downside to all this is that you may find it a little verbose with having to use classes and having to implement the INotifyPropertyChanged on the class but I guarantee you, this will save you a lot of trouble in the long run. I'd advise you to learn a little bit about data binding.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Simple for to loop

    Quote Originally Posted by Niya View Post
    clicking the button ages each person by 10 years.
    It sure feels like that, sometimes
    My usual boring signature: Nothing

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width