2014-09-21 63 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