|
-
Feb 18th, 2023, 06:10 AM
#1
Thread Starter
Addicted Member
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
-
Feb 18th, 2023, 06:28 AM
#2
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.
-
Feb 19th, 2023, 06:00 AM
#3
Thread Starter
Addicted Member
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
-
Feb 19th, 2023, 09:26 AM
#4
Re: Simple for to loop
 Originally Posted by GideonE
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.
-
Feb 19th, 2023, 12:35 PM
#5
Re: Simple for to loop
Hi Gideon,
Are you asking for a way to call the function from the RowStateChanged event?
-
Feb 19th, 2023, 12:49 PM
#6
Re: Simple for to loop
 Originally Posted by schoemr
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
...
-
Feb 19th, 2023, 12:56 PM
#7
Re: Simple for to loop
O okay, seems like infinite loop..
-
Feb 19th, 2023, 01:05 PM
#8
Re: Simple for to loop
 Originally Posted by schoemr
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.
-
Feb 19th, 2023, 01:32 PM
#9
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
 
-
Feb 19th, 2023, 01:50 PM
#10
Re: Simple for to loop
 Originally Posted by Shaggy Hiker
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.
-
Feb 19th, 2023, 03:04 PM
#11
Re: Simple for to loop
 Originally Posted by GideonE
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.
-
Feb 19th, 2023, 03:08 PM
#12
Re: Simple for to loop
 Originally Posted by Niya
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|