WPF avoid adding a duplicate row

故事扮演 提交于 2019-12-25 11:56:35

问题


I'm using vb.net framework 4.5 and WPF project.

I have a button, the function adds a certain product info to a datagrid. In my vb code file I set a product class

Public Class MyProduct
    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemUnitPrice As Double
    Public Property ItemQty As Integer
End Class

The button touchdown event

Private Sub Button_TouchDown(sender As Object, e As TouchEventArgs)

        Dim dmb As New MyProduct
        dmb.ItemNumber = "abc001"
        dmb.ItemDescription = "bla bla bla"
        dmb.ItemQty = 1
        dmb.ItemUnitPrice = 123.45

        MyDataGrid.Items.Add(dmb)

End Sub

Currently, if I tap multiple times of this button, the data grid will add multiple duplicated rows for same product. My goal is when multiple same product add to datagrid, only one row shows and each additional tap/click action on the same button will only increase the ItemQty number.

How can I do that? Thanks!


回答1:


First, you need to prevent inserting twice :

Private Sub buttonAdd_Click(sender As Object, e As RoutedEventArgs) Handles buttonAdd.Click
    Dim dmb As New MyProduct
    dmb.ItemNumber = New Random().Next(5).ToString()
    dmb.ItemDescription = "bla bla bla"
    dmb.ItemQty = 1
    dmb.ItemUnitPrice = 123.45

    Dim dmbSearched As MyProduct = Nothing
    For Each dmbs As MyProduct In MyDataGrid.Items
        If dmbs.ItemNumber = dmb.ItemNumber Then
            dmbSearched = dmbs
            Exit For
        End If
    Next

    If dmbSearched Is Nothing Then
        MyDataGrid.Items.Add(dmb)
    Else
        dmbSearched.ItemQty += 1
    End If
End Sub

Second the MyProduct class must raise an event when the quantity is changed, otherwise there is no visible change :

Public Class MyProduct : Implements INotifyPropertyChanged
    Private Property m_ItemQty As Integer
    Public Property ItemQty As Integer
        Get
            Return m_ItemQty
        End Get
        Set(value As Integer)
            m_ItemQty = value
            FirePropertyChanged()
        End Set
    End Property
    Public Sub FirePropertyChanged(<CallerMemberName> Optional propName As String = "")
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
    End Sub
    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemUnitPrice As Double

End Class

Regards



来源:https://stackoverflow.com/questions/32893206/wpf-avoid-adding-a-duplicate-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!