VB DataGridView计算?

时间:2014-09-21 05:32:23

标签: vb.net datagridview

这是我的代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.Columns.Clear()
    Dim newTable As New DataTable

    newTable.Columns.Add("Column1")
    newTable.Columns.Add("Column2")
    newTable.Columns.Add("Column3")

    newTable.Rows.Add("1", "4", "")
    newTable.Rows.Add("10", "2", "")
    newTable.Rows.Add("20", "5", "")

    DataGridView1.DataSource = newTable

    Try
        Dim iCell1 As Integer
        Dim icell2 As Integer
        Dim icellResult As Integer
        iCell1 = DataGridView1.CurrentRow.Cells(0).Value
        icell2 = DataGridView1.CurrentRow.Cells(1).Value
        icellResult = iCell1 * icell2
        DataGridView1.CurrentRow.Cells(2).Value = icellResult
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub

Column3 = column1 * column2。 在我上面的代码中,只在第1行正确。我希望第3列显示为值4,20和100。

3 个答案:

答案 0 :(得分:0)

尝试

For i As Integer = 0 To 2
        newTable.Rows(i).Cells(2).Value = newTable.Rows(i).Cells(0).Value * newTable.Rows(i).Cells(1).Value
    Next 

答案 1 :(得分:0)

你的代码就像这样

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.Columns.Clear()
    Dim newTable As New DataTable

    newTable.Columns.Add("Column1")
    newTable.Columns.Add("Column2")
    newTable.Columns.Add("Column3")

    newTable.Rows.Add("1", "4", "")
    newTable.Rows.Add("10", "2", "")
    newTable.Rows.Add("20", "5", "")

    DataGridView1.DataSource = newTable

    Try
       For i As Integer = 0 To 2
        newTable.Rows(i).Cells(2).Value = newTable.Rows(i).Cells(0).Value * newTable.Rows(i).Cells(1).Value
        Next 

    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub

答案 2 :(得分:0)

我认为这适用于您的代码

 Private Sub DataGridView1_CellValueNeeded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValueNeeded
    With DataGridView1
        If e.ColumnIndex = 2 And Not (TypeOf (.Rows(e.RowIndex).Cells(0).Value) Is DBNull OrElse _
                                      TypeOf (.Rows(e.RowIndex).Cells(1).Value) Is DBNull) Then
            Dim i, j As Integer

            i = CInt(.Rows(e.RowIndex).Cells(0).Value)
            j = CInt(.Rows(e.RowIndex).Cells(1).Value)
            e.Value = i * j
        End If
    End With
End Sub