How to AddHandler to Multiple Items and Properly Reference Said Handler - vb.net

I'm writing a program wherein I need to create GotFocus and LostFocus event handlers for every text box.
What I have now creates an error whenever any text box in the form is clicked on:
Private Sub lblTotalWeight_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each cnt In Me.Controls.OfType(Of TextBox)
AddHandler cnt.GotFocus, AddressOf txtBox_GotFocus
Next
End Sub
Private Sub txtBox_GotFocus(sender As System.Object, e As System.EventArgs)
Dim textBox As TextBox = Me.Controls.OfType(Of TextBox)
textBox.ForeColor = Color.White
textBox.BackColor = Color.LightGray
End Sub
I'm getting an error with the Dim textBox as TextBox = Me.Controls.OfType(Of TextBox), and I have no idea why or how to fix it.
There will be another Private Sub for a lost focus event that will be nearly identical, if it helps.
Any help would be appreciated

Me.Controls.OfType(Of TextBox) returns a list of controls that are textboxes. It works great in your AddHandler call, but in your event handler you need to use sender as Textbox instead.
Dim textBox As TextBox = DirectCast(sender, Textbox)

This code:
Me.Controls.OfType(Of TextBox)
returns an IEnumerable(Of TextBox). It's not a single Textbox so you can't assign it to a TextBox variable. You need to access the TextBox that raised the event:
Dim textBox As TextBox = DirectCast(sender, TextBox)
In an event handler, the sender parameter is always the object that raised the event.

Me.Controls.OfType(Of TextBox) with replace CType(sender, TextBox) for event txtBox_GotFocus

Related

Why doesn't Me.Controls.OfType work in VB.NET?

I'm using .NET Framework 4.7.2 for reference.
I'm using Me.Controls.OfType for automated handles in an event in my form.
Sub AddTextBoxes_TextChanged()
Dim textboxes = Me.Controls.OfType(Of TextBox)()
Console.WriteLine(textboxes.Count)
For Each txt In textboxes
AddHandler txt.TextChanged, AddressOf AllTextBoxes_TextChanged
Next
End Sub
Private Sub SampleForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddTextBoxes_TextChanged()
End Sub
Private Sub AllTextBoxes_TextChanged(sender As Object, e As EventArgs)
' ...
End Sub
However, the For loop doesn't work, so I checked if there are actual textbox controls within textboxes with Console.WriteLine(textboxes.Count). Well, the result is 0. I've checked multiple times in the Form Design for textboxes, and they exist. Why doesn't Controls.OfType(Of TextBox)() work?
Place your handler in the code for the form.
In design view select the one of the text boxes.
In the Properties window select the lightning bolt to display all the events available for a TextBox. Choose the TextChanged event and the drop down box arrow. Your AllTextBoxes_TextChanged method will be listed because the signature matches. Select your method and the Handles code will be added to the method.
Do the same for each text box you wish to use this method.
Of course you can always type the extended Handles clause.
However, I don't see what is wrong with your code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim textboxes = Controls.OfType(Of TextBox)() '.ToList
For Each txt In textboxes
AddHandler txt.TextChanged, AddressOf AllTextBoxes_TextChanged
Next
End Sub
Private Sub AllTextBoxes_TextChanged(sender As Object, e As EventArgs)
Dim tb = DirectCast(sender, TextBox)
MessageBox.Show($"The text changed event fired by {tb.Name}")
End Sub
Works for me.

Clear focused textbox in multiple textboxes in vb.net using delete key

I want a good example of clearing focused textbox among multiple textboxes using delete key. Please help me providing vb.net code.
The public sub is as such :
Public Sub EmptyTxt(ByVal Frm As Form)
Dim Ctl As Control
For Each Ctl In Frm.Controls
'If TypeOf Ctl Is TextBox Then Ctl.Text = ""
Next
End Sub
Then I call this sub from delete keydown event. But it clears all textboxes rather than clearing the focused one.
There's an easier way to do that.
Simply assign all the textbox keyDown events to the same handler. In that handler, cast sender to a textbox and clear it.
Private Sub Form1_Load (sender As Object, e As EventArgs) Handles MyBase.Load
For Each tb As TextBox In Controls.OfType(Of TextBox)
AddHandler tb.KeyDown, AddressOf TbKeyDown
Next
End Sub
Private Sub TbKeyDown (sender As Object, e As KeyEventArgs)
Dim tb = CType(sender, TextBox)
If e.KeyCode = Keys.Delete Then
tb.Clear()
End If
End Sub

Visual Indication of Focus and Adding Click Event To all TextBoxes

I'm working on a program wherein I have around 400 Text Boxes and I need to program an effect to make them show that they have focus. I can get the visual part down (Unless someone knows how to add a soft blue outline to a text box in VB), but I'm having trouble with creating GotFocus and LostFocus events that handle all of my Text Boxes at once. I've tried
Dim txtBox = Me.Controls.OfType(Of TextBox)
Private Sub TextBox_GotFocus(sender As Object, e As EventArgs) Handles txtBox.GotFocus
But I get a "Must have WithEvents variable" error which I don't quite understand how to fix. I've tried
Public Sub txtBoxGotFocusHandler(ByVal sender As Object,
ByVal e As System.EventArgs)
For Each txtBox As TextBox In Me.Controls 'References all text boxes in form
If txtBox.Focus = True Then
txtBox.BackColor = Color.Black
End If
Next
And I've tried a few other somewhat related things I've seen around the internet, but to no avail. Any help would be appreciated
You can make your app at runtime with any controls. You could query the layout of your app from SQL and from a simple change your app layout changes.
Private FocusRectangle As System.Drawing.Graphics
Private OldRectangle As System.Drawing.Graphics
Private MyTextBoxes As New List(Of TextBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyTextBoxes.Clear()
For xcount = 0 To 399
MyTextBoxes.Add(New TextBox)
With MyTextBoxes.Item(xcount)
.Name = "MyTextBoxes" & (xcount + 1).ToString
.Text = ""
.Location = New Point(0, 0)
.Size = New Size(50, 13)
.Visible = True
AddHandler .GotFocus, AddressOf MyTextBoxes_GotFocus
AddHandler .LostFocus, AddressOf MyTextBoxes_LostFocus
End With
Me.Controls.Add(MyTextBoxes.Item(xcount))
'add them to a panel....
'Panel1.Controls.add(MyTextBoxes.Item(xcount))
Next
End Sub
Sub MyTextBoxes_GotFocus(sender As Object, e As EventArgs)
Dim ThisTextBox As TextBox = DirectCast(sender, TextBox)
Dim xPen As New System.Drawing.Pen(Color.LightBlue)
FocusRectangle = Me.CreateGraphics()
FocusRectangle.DrawRectangle(xPen, ThisTextBox.Location.X - 1, ThisTextBox.Location.Y - 1, ThisTextBox.Size.Width + 1, ThisTextBox.Size.Height + 1)
OldRectangle = FocusRectangle
End Sub
Sub MyTextBoxes_LostFocus(sender As Object, e As EventArgs)
Dim ThisTextBox As TextBox = DirectCast(sender, TextBox)
OldRectangle.Dispose()
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
MyTextBoxes.Item(0).Focus()
End Sub
If you created your form with the Designer, the WithEvents is added for you automatically.
If you are declaring 400 text boxes as Private fields, you would declare them as Private WitheEvents txtBox As TextBox
If you're creating the text boxes programatically and adding them to a collection of textboxes or something, then you can't do WithEvents.
But all WithEvents does is allow you to add Handeles TextBox.SomeEvent to a function. Instead you can do this:
Dim txtBox As New TextBox
...
AddHandler txtBox.GotFocus, AddressOf txtBoxGotFocusHandler
Me.Controls.Add(txtBox)

Detecting the ID of checkbox that was checked

I am making a windows form application. I want to detect which checkbox is being selected by the user. One way to check this would be to loop through all the controls everytime a checkbox checkchanged event is fired. But I do not want to do that because multiple checkboxes could be checked. I want to get the ID of checkbox as it is selected or on a mousedown event. How can I do so?
You can add the event handlers for the checkboxes you want at runtime. Use the Where clause to filter by name if applicable. This code does it in form_load.
Inside the handler, you can cast sender to a local variable which represents the checkbox which was checked, if you want.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each checkBox In Me.Controls.OfType(Of CheckBox)().Where(Function(cb As CheckBox) cb.Name.Contains("CheckBox"))
AddHandler checkBox.CheckedChanged, AddressOf checkboxCheckedChanged
Next
End Sub
Private Sub checkboxCheckedChanged(sender As Object, e As EventArgs)
Dim myCheckbox As CheckBox = DirectCast(sender, CheckBox)
Dim c As Boolean = myCheckbox.Checked
Dim n As String = myCheckbox.Name
' etc.
End Sub
EDIT
As Neolisk pointed out, this doesn't account for nested controls, i.e. controls inside containers on the form. This extension method returns all those controls:
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
Dim result As New List(Of Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(ctrl)
result.AddRange(ctrl.ChildControls(Of T)())
Next
Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function
And make this the loop in form_load instead:
For Each checkBox In Me.ChildControls(Of CheckBox).Where(Function(cb As CheckBox) cb.Name.Contains("CheckBox"))
AddHandler checkBox.CheckedChanged, AddressOf checkboxCheckedChanged
Next
Use sender argument in the event handler.
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) _
Handles CheckBox1.CheckedChanged
'DirectCast(sender, CheckBox).Name ?
End Sub

Datagridview Control modifies another

I'm trying to add values to my second combobox based on the choice of my first combobox in my datagridview (which contains textbox columns as well).
Here's my code:
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Try
'Sub Recurrence combobox is selected
If DataGridView1.CurrentCell.ColumnIndex = 4 Then
'Verify what is chosen in the Recurrence textbox
Dim rowIndex = DataGridView1.CurrentCell.RowIndex
Dim FirstComboboxValue = DataGridView1(3, rowIndex).Value
If Not IsNothing(FirstComboboxValue) Then
Dim cmb As ComboBox = TryCast(e.Control, ComboBox)
RemoveHandler cmb.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
AddHandler cmb.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
End If
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
My handlers fire the trigger towards the ComboBox_SelectedIndexChanged event:
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
If DataGridView1.CurrentCell.ColumnIndex = 4 Then
Dim comboBox As ComboBox = CType(sender, ComboBox)
Dim cbCell As DataGridViewComboBoxCell = DirectCast(DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(4), DataGridViewComboBoxCell)
Dim rowIndex = DataGridView1.CurrentCell.RowIndex
Dim FirstComboboxValue = DataGridView1(3, rowIndex).Value
'Clear items so they don't keep adding on each other
cbCell.Items.Clear()
Select Case FirstComboboxValue
Case "Choice1"
cbCell.Items.Add("Item1")
cbCell.Items.Add("Item2")
Case "Choice2"
cbCell.Items.Add("Item3")
cbCell.Items.Add("Item4")
Case "Choice3"
cbCell.Items.Add("Item5")
Case "Choice4"
cbCell.Items.Add("Item6")
cbCell.Items.Add("Item7")
End Select
'Remove event handler to prevent memory leak
RemoveHandler comboBox.SelectedIndexChanged, AddressOf ComboBox_SelectedIndexChanged
End If
End Sub
For some reason, when I use a break-point and step through the program, the items get added in the second combobox only on the 2nd time that I try ty open the "item" combobox.
If I try to run the program without debugging, nothing is displayed. Any idea what I'm doing wrong?
If you are using SelectedIndexChanged in your ComboBox may be you encounter a problem with events being fired even if you did not click the ComboBox.
This happens when you open and close your Windows Form.
A better one for this by using the SelectionChangeCommitted event.
SelectionChangeCommitted event occurs when the selected item has changed and that change is displayed in the ComboBox.
By using SelectionChangeCommitted event you do not need to declare RemoveHandler and AddHandler statement.
Another possibility:
Try it with Handles cmb.SelectedIndexChanged
There are several ways to declare events in VB.NET. The usual one is using the handles keyword.
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object,
ByVal e As EventArgs) Handles cmb.SelectedIndexChanged