2014-06-07 3 views
0

datagridview의 두 열을 곱하고 동일한 열 3의 제품을 표시하려면 datagridview.DataGridView Vb에서 셀 자동 계산

Column1 - Column2 - Column3 

12   2  24 

15   2  30 

은 여기 내 코드

Private Sub Table1DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles Table1DataGridView1.CellValidated 
    Try 
     Dim iCell1 As Integer 
     Dim icell2 As Integer 
     Dim icellResult As Integer 
     iCell1 = Table1DataGridView1.CurrentRow.Cells(1).Value 
     icell2 = Table1DataGridView1.CurrentRow.Cells(2).Value 
     If String.IsNullOrEmpty(iCell1) OrElse String.IsNullOrEmpty(icell2) Then Exit Sub 
     If Not IsNumeric(iCell1) OrElse Not IsNumeric(icell2) Then Exit Sub 
     icellResult = CDbl(iCell1) * CDbl(icell2) 
     Table1DataGridView1.CurrentRow.Cells(3).Value = icellResult 
    Catch ex As Exception 
     MessageBox.Show(ex.ToString) 
    End Try 
End Sub 

그것은 작동하지만 새 행 나중에 추가된다. 그러니 도와주세요.

우리는 내가 MultiplyPair 전화, 새로운 클래스를 만들 :

답변

0

우아한 방법은 데이터 바인딩 (datagridviews와 함께 빵과 버터 방법)을 사용하는 것입니다. 이 클래스는 기본적으로 변경 가능한 속성 인 Value1Value2을 가지고 있습니다. 또한 읽기 전용 속성 인 Product이 있습니다. Value1 또는 Value2이 변경 될 때마다 INotifyPropertyChanged를 구현하여 제품이 변경된 바인딩 소스에 통지합니다.

이 가지고 몇 가지 장점 :

  • 당신은 수동 편집하는 동안 발생할 수있는 DGV의 많은 단점을 피하기
  • 그것은 그냥 자신이를 사용하기 시작 해요 (데이터 바인딩을 사용하는 방법을 배우게 할 수있는 좋은 방법입니다 개념이 철저하니 놀랍습니다.)
  • 쉽게 적응할 수 있습니다. 제품, 합계 및 지수를 원하십니까? 속성 및 간단한 알림을 추가하기 만하면됩니다.
  • 구조가 명확하므로 다른 사람들이 코드를 이해할 수 있습니다.
  • 전체 로직을 재사용 할 수 있으며 다른 데이터 그램 뷰를 동일한 바인딩 목록에 바인딩하면 코드가 거의없는 여러 위치에서 정보를 표시하고 변경할 수 있습니다.

우리는 Bindinglist (Of MultiplyPair)를 만들고이 목록을 DataGridview에 바인딩합니다. 그런 다음 목록에 값을 입력하면 datagridview가 자동으로 채워집니다. Datagridview에서 값을 변경할 수도 있으며 제품이 자동으로 업데이트됩니다.

Public Class Form1 
    Private WithEvents Values As New System.ComponentModel.BindingList(Of MultiplyPair) 'This holds one object for every line in the DGV 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     Values = New System.ComponentModel.BindingList(Of MultiplyPair) 'Initialize the list 
     DataGridView1.AllowUserToAddRows = False 'Disallow new rows, as per your question 
     DataGridView1.DataSource = Values 'Bind the list to the datagridview 
     'Add two example lines 
     Values.Add(New MultiplyPair With {.Value1 = 2, .Value2 = 12}) 
     Values.Add(New MultiplyPair With {.Value1 = 15, .Value2 = 2}) 
    End Sub 
End Class 

Public Class MultiplyPair 
    Implements System.ComponentModel.INotifyPropertyChanged 
    'The first value 
    Private _Value1 As Double 
    Public Property Value1 
     Get 
      Return _Value1 
     End Get 
     Set(value) 
      _Value1 = value 
      'Notify not only that Value1 has changed, but also that the Product has changed 
      Notify("Value1") 
      Notify("Product") 
     End Set 
    End Property 
    'Same as above 
    Private _Value2 As Double 
    Public Property Value2 
     Get 
      Return _Value2 
     End Get 
     Set(value) 
      _Value2 = value 
      Notify("Value2") 
      Notify("Product") 
     End Set 
    End Property 
    'This will show the product of Value1 and Value2 whenever asked 
    Public ReadOnly Property Product 
     Get 
      Return Value1 * Value2 
     End Get 
    End Property 

    'Helper sub to raise the PropertyChanged event with the given Propertyname 
    Private Sub Notify(name As String) 
     RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs(name)) 
    End Sub 

    'INotifyPropertyChanged implementation 
    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged 
End Class 

편집 : 추가 행을 방지하려면, false로 DataGridView에의 AllowUsersToAddRows 속성을 설정합니다.