Link to home
Start Free TrialLog in
Avatar of Ryan_R
Ryan_RFlag for Australia

asked on

Find out which control had focus

Hi all

I have a series of text boxes in VB .NET 2008 Express
Named txtCmd01 through to txtCmd20

I have one cmdBrowse button.

When a text box get's focus, the browse button moves to the same .Top property as the textbox - this looks a lot better than having 20 cmd buttons.
The cmd button will open a dialog box to select a file. The filename has to be returned the textbox that had the focus however.

Do you know how I can do this?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of anyoneis
anyoneis
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Alternatively, you can do something like this.


    Private Sub txtCmd02_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCmd01.GotFocus, txtCmd02.GotFocus
        'If all are textboxes
        'This example shows you only two textboxes
        Dim TB As TextBox = sender
        Select Case TB.Name
            Case "txtCmd01"
                'Do here
            Case "txtCmd02"
                'Do here
        End Select
    End Sub
Avatar of Ryan_R

ASKER

Ok. Can you clarify what commands to use?
cmdBrowse.Tag = ???
 
 
???.Text = opnFile.Filename

Open in new window

The Tag is property is a reference to an object, so it can hold anything,

//TextBox GotFocus event
...
cmdBrowse.Tag =  sender;
...
//

// In the Button Click handler, after return from dialog

Control theButton = sender as Button
TextBox theTextBoxPartner = theButton.Tag as TextBox;
theTextBoxPartner.Text = theFileNameText;

//

DAvid

Avatar of tasky
tasky

You can declare a private reference to the textbox within the form

Dim txtSel As TextBox

Then when a textbox gets focus, set the reference of txtSel to the textbox. I.e.:

Private Sub txtCmd02_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCmd01.GotFocus, txtCmd02.GotFocus

txtSel = sender

End Sub

Then when you click the command button, just use txtSel and it will point to the last selected textbox.
Avatar of Ryan_R

ASKER

I had started off using the global variable option, then had doubts, asked this question, then realised my initial method would work.

I'll split the points anyway.