Question Smallest Value in DataGridView Column

BleepyEvans

Active member
Joined
May 2, 2011
Messages
41
Programming Experience
1-3
Hi guys, ive been working on a stopwatch project as some of you know.

Ive created the stopwatch, and thanks to some of your members, I finally got the stopwatch to add the timings into a datagridview every time the lap button is pressed.

Although because im converting the times to strings im having trouble trying to get the smallest value for the fastest lap.

Here what some of my form looks like:
Untitled-1.png

And some of my code:
Private Sub LapButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LapButton.Click
        i += 1
        If DataGridView1.Rows.Count > 0 Then
            DataGridView1.Rows.Add(i, StopwatchLabel.Text, laptimerer.Text)
        Else
            DataGridView1.Rows.Add(i, StopwatchLabel.Text, StopwatchLabel.Text)
        End If
        Label3.Text = Label3.Text + Val(1)
        lapTime = DateTime.Now
    End Sub


    Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartButton.Click
        startTime = DateTime.Now
        StartStopWatch()
    End Sub


 Public Sub StartStopWatch()
        startTime = DateTime.Now
        StopWatch.Start()
        InRaceCountDownTime = DateTime.Now.AddMinutes(racelength.Text)
        InRaceCountDownTimer.Start()
        ProgressBar1.Value = 0
        lapTime = DateTime.Now
        Lap.Start()
    End Sub


 Private Sub Lap_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Lap.Tick
        Dim span As TimeSpan = DateTime.Now.Subtract(lapTime)
        laptimerer.Text = span.Minutes.ToString & ":" & span.Seconds.ToString & "." & span.Milliseconds
      End Sub


Any ideas guys?
 
Yes but that part of the code works fine. That just adds the first row into the datagrid and with the first row I get no errors.

Its the second, third etc rows that cause the error which is the code you made up.

-

If your getting fussy then yes, adding a string into a cell thats format for a timespan shouldnt work, but it does, so i didnt bother trying to fix something that didnt need fixing. So unless adding a string into a cell thats format for a timespan changes the format from timespan to string then I dont see how this is the cause of the problem.
 
Forget the format. That's not the issue. The issue is that you are adding a String to that column and then, when you try to calculate the minimum value in that column, your code is trying, and failing, to cast that String as a Date. I will say one last time, do not add Strings to that column. I said back in post #2 to store DateTimes, which would explain why the code I provided to use that data assumes that the data is DateTimes.
 
Refering back to the 9th Post and "While im here, can I just check, that this finds the smallest value in the column, not row?"

as even when changing the column to spans I still get the same error.

VB.NET:
Private Sub LapButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LapButton.Click
        Dim lapspan As TimeSpan = DateTime.Now.Subtract(lapTime)
        Dim span As TimeSpan = DateTime.Now.Subtract(startTime)
        i += 1

        If DataGridView1.Rows.Count > 0 Then

            Dim minTime As TimeSpan = (From row In Me.DataGridView1.Rows.Cast(Of DataGridViewRow)()
                           Where Not row.IsNewRow
                           Select CDate(row.Cells(3).Value).TimeOfDay).Min()
            DataGridView1.Rows.Add(i, span, lapspan, minTime)

        Else

            DataGridView1.Rows.Add(i, span, span, span)

        End If
        Label3.Text = Label3.Text + Val(1)
        lapTime = DateTime.Now

    End Sub
 
Last edited:
If you're not going to read the replies then there's not much point asking the questions. I said:
I said back in post #2 to store DateTimes, which would explain why the code I provided to use that data assumes that the data is DateTimes.
Is a TimeSpan a DateTime? Obviously not, which would explain why you get an error when trying to cast as type DateTime. Let me say one more time: STORE DATETIME VALUES IN THE GRID. If you don't know how to create a DateTime when what you have is a TimeSpan then the logical course of actiuon would be to ask how to do that. You can do it like this:
VB.NET:
Dim myDateTime = Date.Today + myTimeSpan
That will create a DateTime with your time and today's date. The date value really doesn't matter, as you will use the TimeOfDay property to get just the time anyway. This assumes that all times will be less than 24 hours, which is not a problem in this instance. This will also have the effect of making your format valid, as it is currently being ignored.
 
Sorry I got confused about the post about TimeSpan formats.

But wont the code you provided earlier cause problems

VB.NET:
Dim minTime As TimeSpan = (From row In Me.DataGridView1.Rows.Cast(Of DataGridViewRow)()
                           Where Not row.IsNewRow
                           Select CDate(row.Cells(3).Value).TimeOfDay).Min()
-

Could you suggest a cell format becausse what ever I try i get this error.

Untitled-1.png
 
Last edited:
Everything I have posted previously is correct and would work, except this:
This will also have the effect of making your format valid, as it is currently being ignored.
In previous versions of .NET, you could not format a TimeSpan. That's why I was suggesting using DateTimes, which have supported formatting from the beginning, i.e. .NET 1.0. I didn't realise that they had added the ability to format TimeSpans in .NET 4.0. I guess I should have looked more closely at the links JohnH provided. Anyway, it will work either way as long as you put the correct type of data in and get the correct type of data out. You must put only one type of data into the grid, i.e. either all DateTimes or all TimeSpans and never Strings. Here's a demo of each in action.
 

Attachments

  • LapTimeDemo with DateTime.zip
    12.6 KB · Views: 23
  • LapTimeDemo with TimeSpan.zip
    12.6 KB · Views: 20
Thanks alot for that.

Can I ask how you got the StopWatch function to work, im just getting errors when I paste ur code into my project?
 
Stopwatch is a class, not a function, and I didn't have to do anything to get it to work. If you were to tell us what the error messages were then we might be able to help.
 
Error 1: Type expected
Error 2: 'StartNew' is not a member of 'System.Windows.Forms.Timer'.

Error 1 Code: Private timer As Stopwatch
Error 2 Code: Me.timer = Stopwatch.StartNew()

-

Also how can I convert the stopwatch into a string so I can see the running time.
 
Last edited:
That second error message doesn't seem to make sense. Maybe it will go away if you fix the first one. If Stopwatch isn't recognised as a type that I can only assume that you haven't imported the System.Diagnostics namespace, which the Stopwatch class is a member of.

You can't convert a Stopwatch to a string any more than you can convert a dog into an orange. If you want to display a String containing the elapsed time measured by the Stopwatch then I suggest that you take a closer look at the code you have already been provided. You already have the answer to your question in your hands.
 
Imports System.Diagnostics
Public Class Form1

    Private timer As StopWatch
    Private lastLapTime As TimeSpan

    Private Sub startButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startButton.Click
        Me.lapTimesGrid.Rows.Clear()
        Me.lastLapTime = TimeSpan.Zero
        Me.timer = StopWatch.StartNew()
    End Sub

    Private Sub lapButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lapButton.Click
        If Me.timer IsNot Nothing AndAlso Me.timer.IsRunning Then
            Dim elapsedTime = Me.timer.Elapsed
            Dim lapTime = elapsedTime - Me.lastLapTime

            Me.lapTimesGrid.Rows.Add(lapTime)
            Me.lastLapTime = elapsedTime
        End If
    End Sub

    Private Sub stopButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles stopButton.Click
        Me.timer.Stop()
    End Sub

    Private Sub bestLapButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bestLapButton.Click
        If Me.lapTimesGrid.RowCount > 0 Then
            Dim bestLap = (From row In Me.lapTimesGrid.Rows.Cast(Of DataGridViewRow)()
                           Select DirectCast(row.Cells(0).Value, TimeSpan)).Min()

            'Display the best lap time in the same format as the grid.
            MessageBox.Show(bestLap.ToString(Me.lapTimeColumn.DefaultCellStyle.Format), "Best Lap")
        Else
            MessageBox.Show("No laps recorded.")
        End If
    End Sub

End Class


I dont get the error when I use the project you attached, but when I paste the entire code into a new project, I get the errors.
Im using Visual Studio 2010 Ultimate.
After your last post I added the import, but still the same errors occur.
Did add and references or anything?

Your code is much differnet to the one I had already used.


Would this be the optimal way to display the elapsed time as a string? I cant test it until I get the rest of the code working.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim elapsedTime = Me.timer.Elapsed
        Label1.Text = elapsedTime.ToString("mm\:ss\:fff")
    End Sub
 
Last edited:
I think that I might know what the issue is. The fact that your code contains "StopWatch" and the class is actually named "Stopwatch" suggest to me that this is a name clash issue. Is your project named "StopWatch" by any chance? If so then that is also the name of the project's default namespace. When you use that name in code, the compiler interprets it as that namespace rather then the class. In that case, you must either change the default namespace for your project or else qualify the Stopwatch class name with its namespace to disambiguate the name.
 
It was thank you.

-

Can I just ask what this
VB.NET:
If Me.timer IsNot Nothing AndAlso Me.timer.IsRunning Then
is about, ive never come across this before as there is now timer in the actuall project.

I get the IF conditions, If the timer isnt 0 and it is running. Just how can I have a timer, without a timer. If that makes sense?

-

Also I get this error after adding 2 more columns to the grid.


Any ideas?
 
Last edited:
'timer' is a Stopwatch variable, not a Timer. In the code I provided, a Stopwatch object is not created and assigned to the 'timer' field until the first time you click the Start button, so it's necessary to check that the field is not Nothing before using it when one of the other buttons is clicked.
 
Back
Top