We help IT Professionals succeed at work.

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
Comment
Watch Question

Software Developer
Top Expert 2006
Commented:
When you get focus, you move the command button, so why not go ahead and store off the control id of the textbox. Put it in a global, or perhaps use the command button's Tag property.

With that, the button has no problem figuring out where to put the filename.

David
   me.ActiveControl.Name.ToString
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
Ryan_RIT Systems Administrator
CERTIFIED EXPERT

Author

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

Open in new window

anyoneisSoftware Developer
Top Expert 2006

Commented:
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

Commented:
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.
Ryan_RIT Systems Administrator
CERTIFIED EXPERT

Author

Commented:
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.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.