vbnewbie
vbnewbie

Reputation: 226

How to create a new event for my own custom control?

I have a class which inherit from Panel, and below are some member in this class

Public ItemName As String
Public Quantity As Integer
Public Price As Decimal
Public DiscountAmount As Decimal

How can I create a event when Quantity or DiscountAmount changed then run a function?

I try to write in this way but I get error:-

Private Sub info_Changed(sender As Object, e As EventArgs) Handles Quantity.Changed, DiscountAmount.Changed
    myFunction()
End Sub

Error: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.

Upvotes: 0

Views: 77

Answers (1)

Mukul Varshney
Mukul Varshney

Reputation: 3141

You need to declare the events in user control and then consume those. See below code. I have created a user control UserControl1. This control raises events when Price or DiscountAmount is changed. The usercontrol is then used in Form1. You can use the same approach to change the Quantity.

Public Class Form1

    Private WithEvents userCntrl As New UserControl1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ChangeValues()

    End Sub

    Private Sub ChangeValues()
        userCntrl.Price = 100
        userCntrl.DiscountAmount = 12
    End Sub

    Private Sub userCntrl_Price_Changed(newValue As Decimal) Handles userCntrl.Price_Changed, userCntrl.DiscountAmount_Changed
        MessageBox.Show("New value = " & newValue.ToString)
    End Sub

End Class


Public Class UserControl1
    Public Event Price_Changed(ByVal newValue As Decimal)
    Public Event DiscountAmount_Changed(ByVal newValue As Decimal)

    Public ItemName As String
    Public Quantity As Integer

    Private Price_ As Decimal
    Public Property Price() As Decimal
        Get
            Return Price_
        End Get
        Set(ByVal value As Decimal)
            If value <> Price_ Then
                RaiseEvent Price_Changed(value)
            End If
            Price_ = value
        End Set
    End Property

    Private DiscountAmount_ As Decimal
    Public Property DiscountAmount() As Decimal
        Get
            Return DiscountAmount_
        End Get
        Set(ByVal value As Decimal)
            If value <> DiscountAmount_ Then
                RaiseEvent DiscountAmount_Changed(value)
            End If
            DiscountAmount_ = value
        End Set
    End Property

End Class

Upvotes: 1

Related Questions