VB.NET - How To Get The Sum, Max, Min, Avg Value Of A DataGridView Column In VB NET
In This VB.NET Tutorial We Will See How To Get The Average, Max, Min, Sum Value From Specific DataGridView Column And Display Them In TextBoxes Using VBNET Programming Language.
Project Source Code:
Public Class VB_Datagridview_Column_Cells_Average_Sum_Max_Min_Value
Private Sub VB_Datagridview_Column_Cells_Average_Sum_Max_Min_Value_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' populate datagridview with some data
Dim rand As New Random()
For i As Integer = 0 To 11 Step +1
dataGridView1.Rows.Add("First Name" + i.ToString(), "Last Name" + i.ToString(), rand.Next(20, 65).ToString())
Next
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
dataGridView1.AllowUserToAddRows = False
' Method 1
TextBoxSum.Text = (From row As DataGridViewRow In dataGridView1.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select Convert.ToInt32(row.Cells(2).FormattedValue)
).Sum().ToString()
TextBoxMax.Text = (From row As DataGridViewRow In dataGridView1.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select Convert.ToInt32(row.Cells(2).FormattedValue)
).Max().ToString()
TextBoxMin.Text = (From row As DataGridViewRow In dataGridView1.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select Convert.ToInt32(row.Cells(2).FormattedValue)
).Min().ToString()
textBoxAvg.Text = (From row As DataGridViewRow In dataGridView1.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select Convert.ToInt32(row.Cells(2).FormattedValue)
).Average().ToString("00.000")
' Method 2
Dim sum As Integer
Dim min As Integer
Dim max As Integer
Dim avg As Double
For i As Integer = 0 To dataGridView1.Rows.Count() - 1 Step +1
sum = sum + dataGridView1.Rows(i).Cells(2).Value
If i = 0 Then
max = dataGridView1.Rows(i).Cells(2).Value
min = dataGridView1.Rows(i).Cells(2).Value
End If
If max < dataGridView1.Rows(i).Cells(2).Value Then
max = dataGridView1.Rows(i).Cells(2).Value
End If
If min > dataGridView1.Rows(i).Cells(2).Value Then
min = dataGridView1.Rows(i).Cells(2).Value
End If
Next
avg = sum / dataGridView1.Rows.Count()
TextBoxSum.Text = sum.ToString()
TextBoxMax.Text = max.ToString()
TextBoxMin.Text = min.ToString()
textBoxAvg.Text = avg.ToString("00.00")
End Sub
End Class
///////////////OUTPUT:
vb.net datagridview column max min sum average value |
Bagikan
VB.NET - How To Get The DataGridView Column Max, Min, Sum, Average Value Using VB NET
4/
5
Oleh
insurance