开发者

Calling Private Functions from combobox

I need to build an application that could run co开发者_如何学Pythonde in private function, based on what user has selected using combobox.

For example combo box has three values, One, Two, Three

If user selects one, code written under Private Function One() runs and vise versa

Thanks

Furqan


An easier way would be to assign a function for when the combo box is selected. Inside your function have a select statement like: (Pesduo)

Function comboSelected

    Case "One"
        call Onefunction()
    Case "Two"
        call Twofunction()

End function


Why are you declaring these as private?

Form controls cannot access private functions. You should declare them as protected.


Here's a way to make it work - assuming Windows Forms.

First, define this class:

Public Class ComboAction

    Public Sub New(ByVal text As String, ByVal action As Action)
        _text = text
        _action = action
    End Sub

    Private _text As String
    Public ReadOnly Property Text() As String
        Get
            Return _text
        End Get
    End Property

    Private _action As Action
    Public ReadOnly Property Action() As Action
        Get
            Return _action
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return Me.Text
    End Function

End Class

Now create a form like this:

Public Class ComboActionForm

    Private Sub ComboActionForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.ComboBox1.Items.Add(New ComboAction("Show Foo", AddressOf Foo))
        Me.ComboBox1.Items.Add(New ComboAction("Show Bar", AddressOf Bar))
    End Sub

    Private Sub Foo()
        System.Windows.Forms.MessageBox.Show("Foo")
    End Sub

    Private Sub Bar()
        System.Windows.Forms.MessageBox.Show("Bar")
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        CType(Me.ComboBox1.SelectedItem, ComboAction).Action.Invoke()
    End Sub

End Class

You can add as many ComboAction classes to the ComboBox as you wish. Each can have any Action you define - private methods or otherwise. The sky is the limit. :-)


See my another post. This works great!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜