2017-08-07 95 views
0

如何計算特定列中datagridview行內容的總和?如何計算vb.net中datagridview中特定列的行值總和

假設這是我的datagridview;

Name  Score 
John  35 
Helen  34 
James  30 

Total  99 

我想計算列「分數」的總和放在文本框中。

感謝您的幫助。

+0

嘗試此鏈接https://social.msdn.microsoft.com/Forums/azure/en-US/44ddc6cf-09e5-4f77-abb5-85650a2cad70/how-to-calculate-total-amount-in-datagridview-柱和行中,vbnet?論壇= vbgeneral – Prathyush

回答

0
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 

我認爲這會幫助你。

0

這樣的事情,

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 
0

我也有這個代碼,解決了我的問題:

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