Setting focus to a textbox control - vb.net

If I want to set the focus on a textbox when the form is first opened, then at design time, I can set it's tabOrder property to 0 and make sure no other form control has a tabOrder of 0.
If I want to achieve the same result at run-time, using code, how should I proceed?
Are there alternatives to using tabOrder?
I assume any run-time code will be in the form's constructor or its onload event handler?
EDIT
In other words I'd like to be able to type straight into the textbox as soon as the form appears without having to manually tab to it, or manually select it.

Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form
Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Show()
TextBox1.Select()
End Sub

I think what you're looking for is:
textBox1.Select();
in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)
From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :
Focus is a low-level method intended primarily for custom control
authors. Instead, application programmers should use the Select method
or the ActiveControl property for child controls, or the Activate
method for forms.

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Select()
End Sub

Using Focus method
Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
yourControl.Focus()
End Sub

To set focus,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.Focus()
End Sub
Set the TabIndex by
Me.TextBox1.TabIndex = 0

Quite simple :
For the tab control, you need to handle the _SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then
TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
TextBox4.Focus()
End If

I think the appropriate event handler to use is "Shown".
And you only need to focus the appropriate text box.
Private Sub Me_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
myTextbox.Focus()
End Sub

create a textbox:
<TextBox Name="tb">
..hello..
</TextBox>
focus() ---> it is used to set input focus to the textbox control
tb.focus()

Related

How to determine which control opens ContextMenuStrip

In my form I have MenuStrip, ContextMenuStrip and DataGridView.
This same ContextMenuStrip is attachetd to one MenuStripItem as "DropDown" and to DataGridView as "ContextMenuStrip". That works good.
Problem is that I have to know what is opening that ContextMenuStrip (MeuStripItem or DataGridView) so I can hide some Items depending on that.
This is my approach where I try to determine if caller is MenuStrip1 which don't work.
Private Sub mycontextmenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mycontextmenu.Opening
If CType(sender, MenuStrip) Is MenuStrip1 Then
ExitToolStripMenuItem.Visible = False
Else
ExitToolStripMenuItem.Visible = True
End If
End Sub
Here error message appears: Unable to cast object of type 'System.Windows.Forms.ContextMenuStrip' to type 'System.Windows.Forms.MenuStrip'.
Please help to solve described problem.
sender is going to be the context menu strip
the source control property will retrieve the owner instance
Private Sub mycontextmenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mycontextmenu.Opening
If mycontextmenu.SourceControl is MenuStrip1 Then
ExitToolStripMenuItem.Visible = False
Else
ExitToolStripMenuItem.Visible = True
End If
End Sub

Fire Validated Event on WinForms ComboBox

I have some logic being handled in the Validated event on a combobox, but would like it to trigger as soon as a selection is made. I can handle the SelectedIndexChanged event separately in order to fire the event, but I'm not sure how to invoke it.
Private Sub ComboSelectedIndexChanged(sender As System.Object, e As System.EventArgs) _
Handles ComboBox1.SelectedIndexChanged
'Fire Validated Event
End Sub
Private Sub ComboValidated(sender As System.Object, e As System.EventArgs) _
Handles ComboBox1.Validated
'Do Something Here
End Sub
I'd rather not call into the method handling the validated event directly,
ComboValidated(Nothing, Nothing)
as it's not precisely what I'm trying to do with the code and it will run a second time when in fact the validated event actually does fire upon losing focus.
What code can I execute to fire the validated event (either by fire the event directly or by causing the control to lose focus)?
Why don't you make it as Sub ..
Private Sub ComboValidated(sender As System.Object, e As System.EventArgs) _
Handles ComboBox1.Validated
InCBValidated()
End Sub
Sub InCBValidated()
'Do Something Here
End Sub
So you just call InCBValidated()
I solved this by making the control lose focus which then fired all the neccessary events. The control happened to be in a groupbox so the easiest way to remove focus was just to give that control focus so the same place on the page was still selected
Private Sub ComboSelectedIndexChanged(sender As System.Object, e As System.EventArgs) _
Handles ComboBox1.SelectedIndexChanged
If ComboBox1.Focused Then GroupBox1.Focus()
End Sub

VB.NET - Handle many textboxes with less code

I got many textboxes (about 10) in a form. I want the text in the textbox to be higlighted whenever it gets foucs. The code for that looks like:
Private Sub txtBillNo_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBillNo.GotFocus
HoverText(txtBillNo)
End Sub
Private Sub HoverText(ByRef ctrl as TextBox)
ctrl.SelectAll()
End Sub
It works perfectly, but I though I could do some code optimization here. Since, I have about 10 textboxes (and many other forms containing several textboxes), I have to HoverText(TextBox) in every Private Sub.. Handles TextBox.GotFocus for every textbox in each form.
I look for any form event (or any other way) that is trigerred when focus is given to another control (textbox) within the form, either by MouseClick or TAB so that HoverText(TextBox) is needed to be written only once for a form.
You can list all your textboxes in the Handles clause:
Private Sub atextbox_GotFocus(ByVal sender As System.Object, ByVal e As _
System.EventArgs) _
Handles txt1.GotFocus, _
txt2.GotFocus, _
txt3.GotFocus, _
(...remaining text boxes..)
txt9.GotFocus, _
txt10.GotFocus
Or you can add handlers to all textboxes when loading the form:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each t In Me.Controls.OfType(Of TextBox)()
AddHandler t.GotFocus, AddressOf HoverText
Next
End Sub
Private Sub HoverText(ByVal sender As System.Object, ByVal e As System.EventArgs)
DirectCast(sender, TextBox).SelectAll()
End Sub
The .NET way to alter the behavior of a class is to derive a new one. That's well supported by VB.NET and Winforms as well. For any class derived from Control, you can intercept an event by overriding the protected OnXxx event where Xxx is the event name. You should be using the Enter event btw. Use Project + Add Class and make the code look like this:
Public Class MyTextBox
Inherits TextBox
Protected Overrides Sub OnEnter(ByVal e As System.EventArgs)
Me.Select(0, Me.Text.Length)
MyBase.OnEnter(e)
End Sub
End Class
Compile. Go back to your form and note that you now have a new control on the top of the toolbox. Drag it on the form and note how it now behaves the way you want it, without writing any code or event handler in your form at all.

Form keyDown not working?

Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.Control Then
MessageBox.Show("aaaa")
End If
End Sub
As you can see, my form will check for when the control key is pressed down.
But it doesn't work. Why?
I am not near a computer now so I can't test this, but when I have wanted to get key events on a form before, I would set Form1.KeyPreview to True (or something similar).
That works fine. I assume you have other controls in your form. One of them will get the focus, never the form. Keyboard input only goes to the control with the focus.
You can set the form's KeyPreview property to True. The Winforms' way is to override the ProcessCmdKey() method.
You need to set KeyPreview to true when loading the form, it should work then
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.KeyPreview = True
End Sub
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
MsgBox(e.KeyChar)
End Sub

How to check focused TextBox in vb.net winforms?

I have multiple textbox in a form. How do I know what textbox the cursor currently is?
Trying to do something like this:
If TextBox2.Focus() = True Then
MessageBox.Show("its in two")
ElseIf TextBox3.Focus = True Then
MessageBox.Show("its in three")
End If
But I think its not working.
TextBox.Focus actually assigns the focus to the given textbox. What you're looking for is TextBox.Focused. :)
In fact, all form controls have the Focused property.
I know this already has an accepted answer but I just think this method is a bit easier and should be up here for people who find this through Google or whatever.
Public focussedTextBox As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each control As Control In Me.Controls
If control.GetType.Equals(GetType(TextBox)) Then
Dim textBox As TextBox = control
AddHandler textBox.Enter, Sub() focussedTextBox = textBox
End If
Next
End Sub
This way you can then just refer to the focussedTextBox at any time. You should make sure that you check that there is a focussedTextBox before you do however becuase when the application first loads there will not be. You can do this using:
If Not focussedTextBox Is Nothing Then
...
End If
Alternatively, you could set focussedTextBox to a TextBox of your choice on form load, either by setting its value or by focussing the TextBox.
Obviously, it will not work if you are calling your code in a Button_Click because when you click the Button then the focus is itself goes to the Button which you have clicked.
You can do two things:
Make a combined Focus event for all TextBoxes and check its Sender object.
Private Sub TextBox_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter, TextBox3.Enter
Dim currTextBox As TextBox = sender
If currTextBox.Equals(TextBox2) Then
MessageBox.Show("it's in two")
ElseIf currTextBox.Equals(TextBox3) Then
MessageBox.Show("it's in three")
End If
End Sub
OR
Take a global string variable, and set its value at each TextBox_Focus event, then check string value in the button click event.
Dim str As String
Private Sub TextBox2_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter
str = "two"
End Sub
Private Sub TextBox3_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.Enter
str = "three"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show("it's in " & str)
End Sub