Skip to content

Instantly share code, notes, and snippets.

@CalvinRodo
Last active August 29, 2015 14:10
Show Gist options
  • Save CalvinRodo/33d841316cbb60c4e090 to your computer and use it in GitHub Desktop.
Save CalvinRodo/33d841316cbb60c4e090 to your computer and use it in GitHub Desktop.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddRow("1",17)
AddRow("2",18)
AddRow("1",17)
AddRow("2", 18)
AddRow("3", 19)
AddRow("4", 20)
AddRow("5", 21)
AddRow("6", 22)
AddRow("7", 23)
AddRow("8", 24)
AddRow("9", 25)
AddRow("10", 26)
AddRow("11", 27)
AddRow("12", 28)
AddRow("13", 29)
AddRow("14", 30)
AddRow("15", 31)
'Add System.Linq to use Linq functionality'
'Get List of miles from collection by first converting the 'datagridviewcollection to an IEnumerable of DataGridViewRow so we can use 'Linq on it
Dim miles as IEnumerable(of DataGridViewRow) = DataGridView1.Rows.Cast(of DataGridViewRow)
Dim totalMiles as Integer = miles.Sum(Function(row) row.Cells(3).Value)
'You can also merge this to one line'
Dim totalMiles1Line as Integer = DataGridView1.Rows _
.Cast(of DataGridViewRow) _
.Sum(Function(r) r.Cells(3).Value)
'The Linq code above is equivelant to the following: '
Dim longWayTotalMiles as Integer
For Each(Dim r as DataGridViewRow in DataGridView1.Rows)
longWayTotalMiles += r.Cells(3)
End For
'If instead you put strings in Cell 3 you could do the following.'
'Please note the parse will throw an exception if there is anything but
'numeric data'
Dim totalMiles1Line as Integer = DataGridView1.Rows _
.Cast(of DataGridViewRow) _
.Sum(Function(r) Integer.Parse(r.Cells(3)))
'The linq code above is equivalent to the following '
'The Linq code above is equivelant to the following: '
Dim longWayTotalMilesFromString as Integer
For Each(Dim r as DataGridViewRow in DataGridView1.Rows)
longWayTotalMilesFromString += Integer.Parse(r.Cells(3))
End For
'Do with the total miles whatever you want to.'
AddRow("TotalMiles", TotalMiles)
End Sub
Private Sub AddRow(day as String, mileage as Integer)
Dim row as new DataGridViewRow()
row.Cells(0).Value = day
row.Cells(3).Value = mileage
'DataGridView.Rows is a DataGridViewRowCollection
'http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection(v=vs.110).aspx
DataGridView1.Rows.Add(row)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintForm1.Print()
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment