majid loze
majid loze

Reputation: 13

How to run same code in click event as the double click event?

I have 4 items in a ListBox and each item does a specific thing when it gets clicked on.

But I also want the double click event to do the same thing as the click event.

I can copy and paste all code from click event into double click event, but then you have lots of code crowding the code page doing the same thing. So what to do about this?

Example:

Private Sub listBox1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) _
    Handles listBox1.DoubleClick

  if listbox1.doubleclick then do the same thing in listbox1.clickevent
  end if

End Sub

Upvotes: 1

Views: 4354

Answers (3)

DJDave
DJDave

Reputation: 915

These solutions only work if the code to be executed is available to the class (Class A), which may not be the case if you are building a library. If the control(s) which should execute the same code are in a class which is going to be instantiated in another class (Class B), and the instatiating class is where the code to be executed will be defined, then you can do this:

Class A

Public Event ListDoubleClickOrClick()

Private Sub HandleListDoubleClickOrClick(sender As Object, e As System.EventArgs) Handles listObject.DoubleClick, listObject.Click
    RaiseEvent ListDoubleClickOrClick()
End Sub

Class B

    private sub theCodeToBeExecuted()

    end sub

    dim objClassA as A
    AddHandler objClassA.ListDoubleClickOrClick, AddressOf theCodeToBeExecuted

Upvotes: 0

Himal
Himal

Reputation: 1371

Try Following Code!

Private Sub ListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click

    ListBox1_DoubleClick(sender, e)

End Sub

Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
    MsgBox(ListBox1.Items.Count)
End Sub

Upvotes: 2

MarkJ
MarkJ

Reputation: 30398

Same routine can handle both events. Code:

Private Sub ListBox1_AllClicks(
     ByVal sender As Object, ByVal e As System.EventArgs) 
    Handles ListBox1.Click, ListBox1.DoubleClick

You can set this up in the listbox properties: view events and use the dropdown next to DoubleClick to choose an existing routine.

Upvotes: 3

Related Questions