![](/img/trans.png)
[英]How to sum datagridview rows.values that are greater than 0 in vb.net
[英]How to calculate the sum of Row values in a specific column in a datagridview in vb.net
如何計算特定列中datagridview行內容的總和?
假設這是我的datagridview;
Name Score
John 35
Helen 34
James 30
Total 99
我想計算“分數”列的總和,將其放在文本框中。
謝謝您的幫助。
像這樣
Dim sumOfScore As Integer = 0
For Each row As DataRow in *yourDataRow*
Dim score As Integer = CInt(row.Item("Score").ToString())
sumOfScore += score
Next
txtYourTextBox.Text = sumOfScore.ToString
我也得到了解決我的問題的代碼:
Private Sub GetSUMofUnits()
Dim total As Integer
For Each row As DataGridViewRow In dgvSubjectsEnrolled.Rows
total += row.Cells(4).Value
Next
txtUnits.Text = total
End Sub
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i,total As Integer
total = 0
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Try
connection.Open()
adapter.SelectCommand = New SqlCommand("SELECT * FROM your_DB_table", connection)
adapter.Fill(ds)
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
total = total + ds.Tables(0).Rows(i).Item(1)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
textbox1.text = total
End Sub
End Class
我認為這會對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.