2014-09-21 75 views
0

这是我的代码:VB的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 

的栏3 =列1列2 *。 在我上面的代码中,只有第一行是正确的。我想第3栏显示值4,20,和100

回答

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 
+0

我必须在哪写代码? – valzz 2014-09-21 11:19:16

+0

在Load子代的末尾,代替DataGridView1.CurrentRow.Cells(2).Value = icellResult – TheCreepySheep 2014-09-21 13:44:59

+0

如果您发现我的答案有帮助,请将其标记为已接受 – TheCreepySheep 2014-09-21 14:50:14

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 
+0

我只显示您的写作地点 – Kishan 2014-09-22 05:31:10

0

我认为这会为你的工作code`代码

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