Vb.net Datagridview如果列数据包含数字,则添加列数据
我有一个像这样的Vb.net Datagridview如果列数据包含数字,则添加列数据,vb.net,datagridview,Vb.net,Datagridview,我有一个像这样的datagridview: ------------------------ | S.N |Data1 | Data2| | 1 | - | 10 | | 2 | 4 | 2 | | 3 | 2 | - | | 4 | 9 | - | ------------------------ | S.N |Data1 | Data2| | 1 | - | 10 | |
datagridview
:
------------------------
| S.N |Data1 | Data2|
| 1 | - | 10 |
| 2 | 4 | 2 |
| 3 | 2 | - |
| 4 | 9 | - |
------------------------
| S.N |Data1 | Data2|
| 1 | - | 10 |
| 2 | 4 | 2 |
| 3 | 2 | - |
| 4 | 9 | - |
| total | 15 | 12 |
-----------------------
我想要这样的结果:
------------------------
| S.N |Data1 | Data2|
| 1 | - | 10 |
| 2 | 4 | 2 |
| 3 | 2 | - |
| 4 | 9 | - |
------------------------
| S.N |Data1 | Data2|
| 1 | - | 10 |
| 2 | 4 | 2 |
| 3 | 2 | - |
| 4 | 9 | - |
| total | 15 | 12 |
-----------------------
我试过这个:
Dim data1 As double = 0
Dim data2 As double = 0
For i As Integer = 0 To DataGridView1.RowCount - 1
data1 += Val(CDbl(DataGridView1.Rows(i).Cells(1).Value))
data2 += Val(CDbl(DataGridView1.Rows(i).Cells(2).Value))
Next
Dim rows As String() = {"Total", data1, data2}
DataGridView1.Rows.Add(rows)
但它显示了一个错误:
我是否可以仅从datagridview
提取数字,并显示其中的sum
并添加到最后的
行
?这将检查空值并确保数据是数字
Dim data1 As double = 0
Dim data2 As double = 0
For i As Integer = 0 To DataGridView1.RowCount - 1
If Not IsDbNull(DataGridView1.Rows(i).Cells(1).Value) AndAlso IsNumeric(DataGridView1.Rows(i).Cells(1).Value) Then data1 += Val(CDbl(DataGridView1.Rows(i).Cells(1).Value))
If Not IsDbNull(DataGridView1.Rows(i).Cells(2).Value) AndAlso IsNumeric(DataGridView1.Rows(i).Cells(1).Value) Then data2 += Val(CDbl(DataGridView1.Rows(i).Cells(2).Value))
Next
Dim rows As String() = {"Total", data1, data2}
DataGridView1.Rows.Add(rows)
现在我得到了我的答案:
Dim data1 As double = 0
Dim data2 As double = 0
For j As Integer = 0 To DataGridView1.RowCount - 1
If Regex.IsMatch(DataGridView1.Rows(j).Cells(1).Value, "^[0-9 ]+$") Then
data1 += Val(CDbl(DataGridView1.Rows(j).Cells(1).Value))
End If
If Regex.IsMatch(DataGridView1.Rows(j).Cells(2).Value, "^[0-9 ]+$") Then
data2 += Val(CDbl(DataGridView1.Rows(j).Cells(2).Value))
End If
Next
Dim rows As String() = {"Total", data1, data2}
DataGridView1.Rows.Add(rows)
您没有告诉您的代码出了什么问题。@LarsTech它显示了从字符串到错误的转换错误。注意这里:->错误消息告诉您出了什么问题。在您的示例中,某些单元格包含“-”,无法转换为双精度
Val
是个坏主意too@Plutonix可能是序列号列中的“total”一词,因为OP在添加摘要行之前可能没有收到错误。无法从字符串“-”转换为双精度。
听起来更像Data1或Data2列中的一个-
条目。,