Question

In Microsoft Access, when you click on a label, the textbox associated with that label gets the focus. As far as I can tell, VB.NET does not have this same functionality. I know I can always add something in to the click event of the label, like so...

TextBox1.Focus()

But I have dozens of fields on the form, and it would make it so much easier if I did not need to add this to the click event of each label.

I guess it would be possible to make an event for all labels that forces a tab to the next control, and assuming that I have the Tab indices set up correctly, then this would work. The problem would occur when adding new fields to the form, in which case all tab indices would need re-verified.

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click, Label2.Click
    'code to tab to next field...
End Sub

Is there any easier way?

Était-ce utile?

La solution

First, set the controls' TabIndex orders on your form then use this code:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each c As Control In Me.Controls
            If TypeOf c Is Label Then AddHandler c.Click, AddressOf Label_Click
        Next
    End Sub

    Private Sub Label_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.SelectNextControl(sender, True, True, True, True)
    End Sub
End Class

Now whenever you click on a label, the following control in the order will be focused.

Autres conseils

How about creating a dictionary where the label is the key and the control to focus is the value, then add a Click event handler to all of the label in the Dictionary. Everytime you add a label/control 'all' you need to do is add another KeyValuePair to the Dictionary

Simple Example:

 Public Class Form1
    Protected Friend DicLabelToControl As Dictionary(Of Label, Control)

    Protected Friend Sub InitLabelDic()
        DicLabelToControl = New Dictionary(Of Label, Control) From {{Label1, TextBox1}, {Label2, TextBox2}}
    End Sub

    Protected Friend Sub AddClickEventsToLabels()
        For Each lb As Label In DicLabelToControl.Keys
            AddHandler lb.Click, AddressOf HandleLabelClick
        Next
    End Sub

    Private Sub HandleLabelClick(sender As Object, e As EventArgs)
        DicLabelToControl(CType(sender, Label)).Focus()

    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        InitLabelDic()
        AddClickEventsToLabels()
    End Sub
End Class
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top