Datagridview添加列数据(如果它包含数字)

时间:2018-04-09 15:10:04

标签: vb.net datagridview

我这样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   |
-----------------------

我试过这个:

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)

但它显示错误:

enter image description here

我是否可以仅从datagridview中提取数字并显示sum 并添加到上一个row

2 个答案:

答案 0 :(得分:1)

现在我得到了答案:

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)

答案 1 :(得分:0)

检查空值并确保数据为数字。

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)