VB.net DataGridView
向各位请教一个问题:怎样才能在VB.net中的datagridview控件中计算每一行的和,并将它加到DataGridView的最后一列?...
向各位请教一个问题:怎样才能在VB. net 中的datagridview控件中计算每一行的和,并将它加到DataGridView的最后一列?
展开
1个回答
展开全部
窗体中有个datagridview1的控件,共有3列,分别是column1,column2,total。
在datagridview1的CellValueChanged事件中加入求和的语句。代码如下:
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
'最后一个单元格的值发生变化时,不计算。
If e.ColumnIndex = DataGridView1.Columns.Count - 1 Then
Exit Sub
End If
Dim Sum As Double = 0
Dim CurrentCellValue As Double
'计算除最后一个单元格以外的单元格的数值和
For i As Integer = 0 To DataGridView1.Columns.Count - 2
Try
CurrentCellValue = CDbl(DataGridView1.Rows(e.RowIndex).Cells(i).Value)
Catch ex As Exception
CurrentCellValue = 0
End Try
Sum += CurrentCellValue
Next
Try
DataGridView1.Rows(e.RowIndex).Cells("Total").Value = Sum
Catch ex As Exception
End Try
End Sub
在datagridview1的CellValueChanged事件中加入求和的语句。代码如下:
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
'最后一个单元格的值发生变化时,不计算。
If e.ColumnIndex = DataGridView1.Columns.Count - 1 Then
Exit Sub
End If
Dim Sum As Double = 0
Dim CurrentCellValue As Double
'计算除最后一个单元格以外的单元格的数值和
For i As Integer = 0 To DataGridView1.Columns.Count - 2
Try
CurrentCellValue = CDbl(DataGridView1.Rows(e.RowIndex).Cells(i).Value)
Catch ex As Exception
CurrentCellValue = 0
End Try
Sum += CurrentCellValue
Next
Try
DataGridView1.Rows(e.RowIndex).Cells("Total").Value = Sum
Catch ex As Exception
End Try
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询