我希望将datagridview
的两列相乘,并在同一datagridview
的第3列中显示该产品。
实施例
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
它可以工作,但之后会添加一个新行。所以请帮忙。
答案 0 :(得分:0)
一种优雅的方法是使用数据绑定(使用datagridviews的面包和黄油方法):
我们创建了一个新类,我称之为MultiplyPair。该类基本上具有可更改的属性Value1
和Value2
。
它还有一个名为Product
的第三个只读属性。
每当Value1
或Value2
发生更改时,我们都会通知任何产品已更改的绑定源(通过实现INotifyPropertyChanged)。
这有几个好处:
要使用该类,我们创建一个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
编辑:要避免其他行,请将Datagridview的AllowUsersToAddRows
属性设置为false。