How to automate TextBox control for Enter key - vb.net

I have to do the following for each textbox control.
If e.KeyCode = Keys.Enter Then
Me.DateDateTimePicker.Focus()
End If
Should there be a For Next loop option, pls mention under which Sub Routine I should code the loop.

From what you're saying, I think this should be placed within the KeyPressed event within the text box you are trying to run this piece of code from. You can also integrate multiple events for many controls into a single method.
Hope this helps!

You can but your code inside a 'KeyUp' event and then alter the 'KeyUp' event of one textbox to handle more than one textbox keyups event, but only one code can be executed for all of them,
check this:
Private Sub ***TextBox1_KeyUp***(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles TextBox1.KeyUp, ***TextBox2.KeyUp***, ***TextBox3.KeyUp***
'*************
'Write your code Here
'*************
End Sub

As others said, you can use only one method to handle multiple events.
Moreover, you can execute sender-customized code:
Sub MyEventHandler(sender as Object, e as Event) Handles obj.ev, obj2.ev, obj3.ev
'Use sender property (properly casted, if necessary)
'to run sender specific code
DirectCast(sender, TextBox).Text = "foo"
End Sub

Related

Triggering an event in VB based on a change in a control in a group box

I have a group box with multiple Checkboxes(food item) and each one has a corresponding NumericUpDown control(quantity). For context, it is for a project based on a restaurant menu. I want to hide a button called btnSave whenever either a checkbox is unchecked or the quantity (NumericUpDown) is changed. I currently have btnSave.Hide under the CheckBox1_CheckedChanged and NumericUpDown1_CheckedChanged SubProcedures but I want to know if there's a way to do this when anything within this group box is changed instead of putting the code under each SubProcedure. Thanks
I think you meant .ValueChanged for the NumericUpDown control. (There is no .CheckedChanged) Although this doesn't matter much in this case, this is a good pattern for future reference. Instead of calling an event call a Sub from your events.
When you have several controls responding to a single Event handler, you can find out which control triggered the event by checking the sender parameter. Since, as you can see, sender is an Object you will have to cast it to the appropriate type to get the properties of a CheckBox.
Private Sub HideSaveButton()
btnSave.Hide
End Sub
Private Sub CheckBoxInGroupBox_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged
HideSaveButton()
Dim WhichCheckBox As CheckBox = DirectCast(sender, CheckBox)
Select Case WhichCheckBox.Name
Case "CheckBox1"
MessageBox.Show("CheckBox1 has changed")
Case "CheckBox2"
MessageBox.Show("CheckBox2 has changed")
End Select
End Sub
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
HideSaveButton()
End Sub

How to share events between forms

So i have a tray icon that should behave the same way between 3 forms. I then created this code:
Private Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
TrayForm.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
Which is used to handle the tray icon. How can i do to share this event between the forms so i don't have to place this same code on every form?
How are event handlers working exactly? I looked online and on MSDN and it is not clear to me.
Thanks
Are you sure that you want to share the event, and not juste the code that will handle the event?
If you don't want to copy and paste your code, which you need to handle the events of more than one form, here's a way to do it:
Declare the sub which contains the code needed to handle the event as a public shared sub. Like this:
Public Shared Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs)
So, now you have a Sub which can handle the event you want to handle from all three forms.
Now, when you initialize those forms, add a line to make the shared Sub handle the event you want it to handle:
AddHandler NotifyIcon1.MouseClick, AddressOf ProjectName.FileName.TrayForm_MouseClick
ProjectName.FileName is meant here to be the path to refer to the shares Sub inside the file where you put it. I usually name it like ProjectNameUtils.vb or something like that.
If you just want to avoid copy and pasting your Sub so you don't have to modify it at several places every time you change something, this could be a way to achieve that.
As Stipulated by Hans Passant:
Sub Eclass_EventHandler(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
Me.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
On the Trayform.VB just did the trick.
But about the shared event. i Have one that would have to be:
Private Sub FormClosingEVENT(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Not FromMenu Then e.Cancel = True
Me.WindowState = FormWindowState.Minimized
'Application.Exit()
End Sub
How should i handle this?

add event on controls - how can i refer to the control itself

I want to add the same event on my multiple textboxes. Let's say for example I want all my textboxes to trim the text value of itself when it has lost focus
my idea is to loop through all the textboxes and to add an event handler to all of it, but how will I refer to the textbox itself, I think it is the same as using the "this" keyword, but it is not available in vb.net - any other recommendations?
In order to get the element which triggered the event you can use the sender parameter of the event and cast it to the required type. It is not clear from the question which platform you are using, but below is the sample code for Windows Forms:
Private Sub txt1_TextChanged(sender As Object, e As EventArgs) Handles txt1.TextChanged
Dim currentTextbox as TextBox = CType(sender, TextBox)
' Do what you want with the textbox
End Sub
Similar principles should apply to Web forms or WPF as well.
Through all the textboxes Use handles for all textboxes
Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) _
Handles TextBox1.LostFocus, TextBox2.LostFocus
Dim txtBox As TextBox = sender
txtBox.Text = Strings.Trim(txtBox.Text)
End Sub

How to write a single click event in Visual Basic?

I have created a form that allow users to close a form by clicking anywhere on the enlarged picture form (There are 3 objects to consider) and go back to the other form, which is called: "frmPhone". There's an actual picture on the form: "frmPhonePics" which is what I'm using to accomplish what I'm trying to do (was unable to insert an image on here. Sorry.) What I want to do is write a single click event to close the large picture form to allow the user to close it absolutely anywhere in the form, but I don't know how to do that. Here's the code I have so far:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click
frmPhone.Show()
Me.Hide()
End Sub
It sounds as though you have a picture on your frmPhonePics form. If you double click that (from the VBA editor), you should be taken to the code - for example, you might see
Private Sub Image1_Click()
End Sub
Now all you have to do is add your code there:
Private Sub Image1_Click()
Me.Hide
frmPhone.Show()
End Sub
Note - the order matters, since frmPhone.Show() will "hijack" the code flow until it's dismissed, and in your code Me.Hide will not execute (so the form will not close) until frmPhone has been dismissed.
You can map the click handler for various object to one thing, if that is what you are asking:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Click, Handles picLarge.Click, Handles otherThing.Click
frmPhone.Show()
Me.Hide() ' should be Me.Close?
End Sub
Not sure why it is MyBase.Click in your code instead of Me.Click. Is this a subclassed form?
I'd strongly suggest using a DoubleClick instead of a single Click. The chances of an errant click doing the wrong thing is very great.
The easiest way is right from the designer. Write the sub routine, then for each control, in the properties window, click the events icon(thunderbolt) and assign the sub routine to the double-click event.
Alternatively, dispense with the Handles clause completely and use a series of Addhandler statements in the Load event handler. If you put a unique string in the names of the controls or if it's all the controls, you can iterate through the controls and use one addhandler statement for all of them
For Each c As Control In Me.Controls
AddHandler c.DoubleClick, AddressOf Ctrl_DoubleClick
Next
Private Sub Ctrl_DoubleClick(sender As Object, e As EventArgs)
'Do stuff
End Sub

Can't set focus on a Windows Forms textbox

I can't seem to get input focus on a textbox when a tab page first comes up (I'm using Windows Forms, VB.NET 3.5).
I have a textbox on a panel on a tab page, and I want the focus to be on the textbox when the tab page comes up. I want the user to be able to start typing immediately in the focused textbox without having to click on the textbox. I have tab stops set in the order I want and the textbox is the first tab stop. The tab stops work except that when the tab page comes up the focus is not on the textbox, i.e. the one that's first in the tab order.
In the Enter event handler of the tab page I call the Focus method of the text box, but it returns False and does nothing, no error messages. I know I can access the text box because
at the same point in the code I can set the text of the text box.
If it matters, the layout of the tab page is a little complicated:
frmFoo/TabControl1/TabPageX/Panel1/Panel2/TextBox1
I want to set the focus on TextBox1.
What's the best way to get the focus on the desired textbox?
If setting focus is the best way, why is the textbox.Focus() method failing?
I would assume you are attempting to set focus in the form load event handler? If so, you need to do a Me.Show() to actually create the onscreen controls before focus can be set. Something along the lines of:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Show()
Application.DoEvents()
TextBox1.Focus()
End Sub
If you don't do the Me.Show(), the form is NOT displayed until the load event is complete.
For the tab control, 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
You will still want to set the initial focus in the load event as shown above if the first field selected is to be the textbox on the tab control.
Try either:
Me.ActiveControl = TextBox1
or
TextBox1.Select()
Do the control.Focus() in the OnShown event. You don't need any of the DoEvents logic which didn't work for me anyway.
You Should Use Selected Event of TabControl
Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
If e.TabPage.Name = "TabPage1" Then
TextBox1.Select()
End If
End Sub
As I have Checked in Both TabControl.Selected and TabPage.Enter Event can set Select TextBox. I think there is some other elements stealing focus. please varify
Any of the solutions I found online don't solve the problem when the control is on a tab page.
However, this works:
(1) set the TabIndex of the control to 0.
(2) In your code that handles the tabpage event, do the following:
SendKeys.Send("{TAB}")
If SendKeys doesn't seem to be a valid statment, make sure you have the following import at the top of your code file:
Imports System.Windows.Forms
I found that the TabControl gets the focus when the Selected event completes. To make this work I used the Paint event of the TabPage to set the focus of the desired object.
Private Sub TabChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tab1.Paint, Tab2.Paint, Tab3.Paint
Select Case sender.Name
Case "Tab1"
Textbox1.Focus()
Case "Tab2"
T3extbox2.Focus()
Case "Tab3"
Textbox3.Focus()
End Select
End Sub
Try the Activated event of the form like this:
Private Sub Form2_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
'SendKeys.Send("{TAB}") this line works too
TextBox1.Focus()
End Sub
That is guaranteed to work.
I once had the same problem but i solved it using the Me.activate() function.