Single checkbox to check multiple checkboxes in Visual Basic - vb.net

Hi good people of stackoverflow, I have created a groupBox1 which contains 39 checkboxes which can be checked individually, and I have created a gropuBox2 which contains single check box called "Check All", What I want is when the "Check All" check box is checked all the 39 checkboxes will be selected and when the "Check All" is unchecked all 39 checkboxes will be unchecked also, Can someone please help? Thank you very much.

If all your controls are in the form ( not in groupbox/pannel) you can use the following code
Dim chk As CheckBox
If checkAll.Checked = True Then
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is CheckBox Then
chk = DirectCast(ctrl, CheckBox)
chk.Checked = True
End If
Next
End If
Updates as per edit and comment:
If you want to find controls inside Groupbox1 means you can do like the following
''' <summary>
''' sets CheckBox.Checked inside a container
''' </summary>
''' <param name="parentControl">the container</param>
''' <param name="chkState">ture or false</param>
''' <remarks>use: checkControls(GroupBox1, True)</remarks>
Public Sub checkControls(ByVal parentControl As Control, chkState As Boolean) '<----Pass the parent control where the checkBoxes belongs
Dim chk As CheckBox = Nothing
For Each ctrl As Control In parentControl.Controls '<-----Change from the above code
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = chkState
End If
Next
End Sub
To check call the function as
checkControls(GroupBox1, True)'<----Since your checkboxes are inside the groupBox1
To uncheck call the function as
checkControls(GroupBox1, False)'<----Since your checkboxes are inside the groupBox1

Here's how I would do it. Filter the controls by type using Enumerable.OfType<T> then iterate the result using Array.ForEach<T>.
Private Sub CheckBoxAll_CheckedChanged(sender As Object, e As EventArgs) Handles CheckAll.CheckedChanged
Array.ForEach(Me.GroupBox1.Controls.OfType(Of CheckBox).ToArray(), Sub(box As CheckBox) box.Checked = Me.CheckAll.Checked)
End Sub

Assuming that there are only 40 checkboxes on the form then this will work
Dim ctrl As Control = Me.GetNextControl(Me, True)
Do Until ctrl Is Nothing
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = True
End If
ctrl = Me.GetNextControl(ctrl, True)
Loop
If there are more than 40 checkboxes then take a look at Neethu Soman's solution.

I've tried the code below and works for me but Bjørn-Roger Kringsjå code works much better:
Private Sub cbxAll_CheckedChanged(sender As Object, e As System.EventArgs) Handles cbxAll.CheckedChanged
If cbxAll.Checked = True Then
cbx01.Checked = True
cbx02.Checked = True
' 3 .. 38
cbx39.Checked = True
Else
cbx01.Checked = False
cbx02.Checked = False
' 3 .. 38
cbx39.Checked = False
End If
End Sub

Related

Select All Controls on Form

I am trying to implement a clear all button on a form that clears the textbox contents and unchecks all checkboxes. The issue is that the controls that need to be accessed are contained within Groupboxes and thus cannot be acessed via Me.Controls collection. I saw a similar post here: VB Uncheck all checked checkboxes in forms, but the answer seems to be more complex than I would expect it should be. Is there any easier way other than in that post.
I tried this code, which logically to me should work but it does not:
'Get textboes and clears them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of TextBox)
ctrControls.Text = ""
Next
Next
'Get checkboxes and unchecks them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of CheckBox)
DirectCast(ctrControls, CheckBox).Checked = False
Next
Next
I know the inner for loops work as I used it to clear each GroupBox individually for a different button on the form.
Any assistance would be appreciated.
Here's one option that should work regardless of the UI hierarchy:
Dim cntrl = GetNextControl(Me, True)
Do Until cntrl Is Nothing
Dim tb = TryCast(cntrl, TextBox)
If tb IsNot Nothing Then
tb.Clear()
Else
Dim cb = TryCast(cntrl, CheckBox)
If cb IsNot Nothing Then
cb.Checked = False
End If
End If
cntrl = GetNextControl(cntrl, True)
Loop
That will follow the Tab order on the form
A recursive function really isn't that difficult:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ClearForm(Me)
End Sub
Private Sub ClearForm(ByVal C As Control)
For Each ctl As Control In C.Controls
If TypeOf ctl Is TextBox Then
ctl.Text = ""
ElseIf TypeOf ctl Is CheckBox Then
DirectCast(ctl, CheckBox).Checked = False
ElseIf ctl.HasChildren Then
ClearForm(ctl)
End If
Next
End Sub
End Class

show tooltip on disabled button inside multiple controls

I would like to display the tooltip on a disabled button, I've tried the code below but it looks not to be working.
I think that's because the button is inside a group box and the group box inside a panel, the panel is inside the form.
the code reported would work only if the button is directly on the form..
Private toolTipShown As Boolean = False
Private Sub TimeWorks_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
Dim parent = TryCast(sender, Control)
If parent Is Nothing Then
Return
End If
Dim ctrl = parent.GetChildAtPoint(e.Location)
If ctrl IsNot Nothing Then
If ctrl.Visible AndAlso toolTip1.Tag Is Nothing Then
If Not toolTipShown Then
Dim tipstring = toolTip1.GetToolTip(ctrl)
toolTip1.Show(tipstring.Trim(), ctrl, ctrl.Width / 2, ctrl.Height / 2)
toolTip1.Tag = ctrl
toolTipShown = True
End If
End If
Else
ctrl = TryCast(toolTip1.Tag, Control)
If ctrl IsNot Nothing Then
toolTip1.Hide(ctrl)
toolTip1.Tag = Nothing
toolTipShown = False
End If
End If
End Sub
Any suggestions to make the code working?

Is it possible to have things defined and controlled inside a class, without being assigned in the "form" (outside the class) in VB?

My problem:
I have a checkbox I use to control if certain textboxes are enabled or not, and I need to do this around 30+ times. I've named my textboxes numerically/sequentially (TB_name_1, TB_name_2, etc) so if I know the Checkbox name I know which textboxes are affected.
My question:
Can I make a class for my checkboxes that says "if this box is checked/unchecked, then enable/disable these 3 textboxes" without the class also having to be told which textboxes (finds them itself)?
Here's the copy/paste code I'm currently using (not a class, obviously). I change the first 2 values and the rest of the code solves itself. (PS - I see you laughing)
Private Sub T1_cb_c_1_CheckedChanged(sender As Object, e As EventArgs) Handles T1_cb_c_1.CheckedChanged
'change here for current checkbox
Dim b As CheckBox = T1_cb_c_1
'change here for start value of first textbox (of 3), the next 2 will be in sequence
Dim a As Integer = 1
'How much of the below code can be moved to, and controlled from, a class?
Dim a1 As Integer = a + 1
Dim a2 As Integer = a + 2
Dim TB_PtNum As TextBox = Me.Controls.Find("T1_tb_c_" & a, True).FirstOrDefault
Dim TB_Qty As TextBox = Me.Controls.Find("T1_tb_c_" & a1, True).FirstOrDefault
Dim TB_Seq As TextBox = Me.Controls.Find("T1_tb_c_" & a2, True).FirstOrDefault
If b.Checked = True Then
TB_PtNum.Enabled = True
TB_Qty.Enabled = True
TB_Seq.Enabled = True
Else
TB_PtNum.Enabled = False
TB_Qty.Enabled = False
TB_Seq.Enabled = False
End If
End Sub
Here's a design time only class that will do this. You only have to the AssociatedCheckbox property in the designer:
Public Class TextBoxWithCheckboxProperty
Inherits TextBox
Private m_CheckBox As CheckBox
Public Property AssociatedCheckBox As CheckBox
Get
Return m_CheckBox
End Get
Set(value As CheckBox)
If Not m_CheckBox Is Nothing Then
RemoveHandler m_CheckBox.CheckedChanged, AddressOf OnCheckBoxChanged
End If
m_CheckBox = value
If Not value Is Nothing Then
AddHandler m_CheckBox.CheckedChanged, AddressOf OnCheckBoxChanged
End If
OnCheckBoxChanged(m_CheckBox, Nothing)
End Set
End Property
Private Sub OnCheckBoxChanged(ByVal sender As Object, ByVal e As System.EventArgs)
If Not sender Is Nothing Then
Me.Enabled = CType(sender, CheckBox).Checked
Else
Me.Enabled = False
End If
End Sub
End Class
Here's a sample Form1 that uses it:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.CheckBox1 = New System.Windows.Forms.CheckBox()
Me.TextBoxWithCheckboxProperty1 = New WindowsApp4.TextBoxWithCheckboxProperty()
Me.SuspendLayout()
'
'CheckBox1
'
Me.CheckBox1.AutoSize = True
Me.CheckBox1.Location = New System.Drawing.Point(293, 131)
Me.CheckBox1.Name = "CheckBox1"
Me.CheckBox1.Size = New System.Drawing.Size(81, 17)
Me.CheckBox1.TabIndex = 0
Me.CheckBox1.Text = "CheckBox1"
Me.CheckBox1.UseVisualStyleBackColor = True
'
'TextBoxWithCheckboxProperty1
'
Me.TextBoxWithCheckboxProperty1.AssociatedCheckBox = Me.CheckBox1
Me.TextBoxWithCheckboxProperty1.Location = New System.Drawing.Point(428, 131)
Me.TextBoxWithCheckboxProperty1.Name = "TextBoxWithCheckboxProperty1"
Me.TextBoxWithCheckboxProperty1.Size = New System.Drawing.Size(100, 20)
Me.TextBoxWithCheckboxProperty1.TabIndex = 1
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.TextBoxWithCheckboxProperty1)
Me.Controls.Add(Me.CheckBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents CheckBox1 As CheckBox
Friend WithEvents TextBoxWithCheckboxProperty1 As TextBoxWithCheckboxProperty
End Class
I would use the property Tag for the related controls.
Suppose to set this property to the value "line1" for the first set of textboxes and on the checkbox that controls them.
Next row of controls (checkbox+textboxes) will have the property set to "line2" and so on until the last row. (You can do this through the Winforms Designer or through code)
At this point you could have a single event handler for all your checkboxes
Private Sub onCheckedChanged(sender As Object, e As EventArgs) _
Handles T1_cb_c_1.CheckedChanged, T2_cb_c_2.CheckedChanged, _
..... add other checkbox events here .......
' Get whatever checkbox has been clicked and extract its tag
Dim b As CheckBox = DirectCast(sender, CheckBox)
Dim tag = b.Tag.ToString()
' Find the textbox controls in this form with the same Tag
Dim ctrls = Me.Controls.OfType(Of TextBox).Where(Function(x) x.Tag.ToString() = tag)
' Enabled status matches the status of the Checked property
For Each c as TextBox in ctrls
c.Enabled = b.Checked
Next
End Sub

Disable textboxes with the corresponding checkboxes in VB.net

Public Class Form1
Dim controlNames() As String = {"Tea", "Cola", "Coffee", "Orange", "Water", "VanillaCone", "VanillaShake", "StrawberryShake", "ChocolateMilkshake", "Fries", "Salad", "Hamburger", "OnionRings", "ChickenSalad", "FishSandwich", "CheeseSandwich", "ChickenSandwich"}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
For Each ctrl As Control In Me.Panel2.Controls
If TypeOf ctrl Is TextBox Then
ctrl.Enabled = False
End If
Next
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs)
For i = 0 To 16
For Each ctrl As Control In Me.Panel2.Controls
If TypeOf ctrl Is CheckBox Then
If ctrl.Name = "chk" & controlNames(i) Then
If DirectCast(ctrl, CheckBox).CheckState = CheckState.Checked Then
If TypeOf ctrl Is TextBox Then
If ctrl.Name = "txt" & controlNames(i) Then
ctrl.Enabled = True
End If
End If
End If
End If
End If
Next
Next
End Sub
I have a VB.NET assignment and I am attempting to enable textboxes based on whether or not the checkbox with the same name was checked.
This is my code so far and it obviously doesn't work. What I want to do essentially:
All textboxes start as disabled. Then, textboxes only get enabled if the corresponding checkboxes are checked. For example, if chkTea is checked, then it enables txtTea.
I am aware I can copy paste something like "if chkTea = checked then txt.tea = enabled". I do not want to do this as this seems like a poor way to go about this. I want to know if I can do something like my barely readable code shows.
If you're renaming all your controls to something different to the default name with a number, this code should work just fine.
You dont need a timer, it just fires when any of the CheckBoxes have their state changed.
In the example code, I've created a CheckedChanged handler and set it to handle some of the CheckBoxes (You'll want to add all those you want to handle). If you click on any of these CheckBoxes, the handler will fire. The handler then passes which checkbox has been changed to the SyncTextBoxWithCheckBoxState method. This then finds the matching textbox using the FindMatchingCheckBox method and sets the .Enabled state of the Text box to the same as the .Checked state of the CheckBox
Private Sub chkTea_CheckedChanged(sender As Object, e As EventArgs) Handles chkTea.CheckedChanged, chkCoffee.CheckedChanged, chkCola.CheckedChanged, chkOrange.CheckedChanged, chkTea.CheckedChanged, chkVanillaCone.CheckedChanged, chkVanillaCone.CheckedChanged, chkWater.CheckedChanged
SyncTextBoxWithCheckBoxState(CType(sender, CheckBox))
End Sub
Private Sub SyncTextBoxWithCheckBoxState(chkBox As CheckBox)
Dim txtBox As TextBox = FindMatchingTextBox(chkBox)
txtBox.Enabled = chkBox.Checked
End Sub
Private Function FindMatchingTextBox(chkbox As CheckBox) As TextBox
For Each ctrl As Control In Panel2.Controls
If ctrl.GetType Is GetType(TextBox) And ctrl.Name.Contains(chkbox.Name.Substring(3)) Then
Return CType(ctrl, TextBox)
End If
Next
Return Nothing
End Function
EDIT
To have the code target more than one panel, add all the checkboxes you want to detect to the event handler like before, and in the FindMatchingTextBox method, just add another loop around the existing one to loop through each panel. Like so ..
Private Function FindMatchingTextBox(chkbox As CheckBox) As TextBox
'This is the new loop which loops through the two panels. It's
'a bit quick and dirty, but it works
For Each pnl As Panel In New Panel() {Panel2, Panel3}
'In this line note that the reference to Panel2 now refers to pnl
For Each ctrl As Control In pnl.Controls
If ctrl.GetType Is GetType(TextBox) And ctrl.Name.Contains(chkbox.Name.Substring(3)) Then
Return CType(ctrl, TextBox)
End If
Next
'End point of the new loop
Next
Return Nothing
End Function
After you've looped through each checkbox, you are only concerned with that checkbox, so when you find the correct checkbox, you need to then RELOOP back through all the controls on the form checking if they are the corresponding textbox.
Something like the below should work, or at the very least start you off down the right path:
Dim controlNames() As String = {"Tea", "Cola", "Coffee", "Orange", "Water", "VanillaCone", "VanillaShake", "StrawberryShake", "ChocolateMilkshake", "Fries", "Salad", "Hamburger", "OnionRings", "ChickenSalad", "FishSandwich", "CheeseSandwich", "ChickenSandwich"}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
For Each ctrl As Control In Me.Panel2.Controls
If TypeOf ctrl Is TextBox Then
ctrl.Enabled = False
End If
Next
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs)
For i = 0 To 16
For Each ctrl As Control In Me.Panel2.Controls
If TypeOf ctrl Is CheckBox Then
If ctrl.Name = "chk" & controlNames(i) Then
If DirectCast(ctrl, CheckBox).CheckState = CheckState.Checked Then
For Each ctrl As Control In Me.Panel2.Controls
If TypeOf ctrl Is TextBox Then
If ctrl.Name = "txt" & controlNames(i) Then
ctrl.Enabled = True
End If
End If
Next
End If
End If
End If
Next
Next
End Sub

VB, Pass variables to a control

I have been tasked with creating a cinema booking system in VB.net by my teacher. So far I have created 50 CheckBoxes and I am trying to rename them all to seat (number). I have this code in my Form1.load but it is not working because it is a type and not an expression. I tried using a variable for this but it did not work.
Here is my code:
For count As Integer = 1 To 54 Step 1
CheckBox(count).text = "Seat " & count
Next
Please help, and or recommend me another way to accomplish this.
set the name of the checkbox when you create it. To find out how to create a checkbox programmatically add a checkbox to a form then look at .designer.vb
dim cb as new checkbox
cb.name = "1"
cb.text = "Seat 1"
you need to also add the location and other properties
If you have already created your textboxes with names like 1, 2 then iterate through and get the numbers like this: If you call them CB_1 then cut the CB_ off before looking for the number.
dim cbNumber as int16
For Each c As Control In myContainer.Controls
If c.GetType() Is GetType(CheckBox) Then
cbnumber = cint(c.name)
c.text = "Seat" & cbnumber
End If
Next
Well, here's my approach. In order to test just drop on a FlowLayoutPanel, a Button, and a NumericUpDownonto the form.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For count As Integer = 1 To 54 Step 1
' Make a new CheckBox
Dim chkBox As New CheckBox()
' Setup the Checkbox
With chkBox
.Tag = count.ToString
.Name = CStr("seatCheckBox" & count.ToString)
.Text = String.Format("Seat {0}", count)
.ThreeState = False
.Checked = False
End With
' add an event listener for the checkbox checkstate changed event
AddHandler chkBox.CheckStateChanged, AddressOf Me.CheckBox_CheckStateChanged
' Add the checkbox to the control
Me.FlowLayoutPanel1.Controls.Add(chkBox)
' Keep the user from picking something that doesn't exist
Me.NumericUpDown1.Maximum = CDec(count)
Next
' Add and event listener for the find button click event
AddHandler Button1.Click, AddressOf Me.FindButton_Clicked
End Sub
' Find the checkbox in the form and return it
Private Function GetCheckBox(ByVal seatNumber As Integer) As CheckBox
Dim chkbox As CheckBox
' Try to find the Checkbox
Try
chkbox = TryCast(Me.Controls.Find(CStr("seatCheckBox" & seatNumber.ToString), True).First, CheckBox)
Catch ex As Exception
chkbox = Nothing
End Try
'Check if the trycast worked
If IsNothing(chkbox) Then
Throw New ArgumentOutOfRangeException("seatNumber", "The seat number to be searched for was not found")
Else
Return chkbox
End If
End Function
' Handle the Chekbox checkState event.
Private Sub CheckBox_CheckStateChanged(sender As Object, e As EventArgs)
' Convert to Checkbox
Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
' Simple result string
Dim resultstring As String = CStr("Seat Number {0} is now {1}.")
' Set the values
Select Case chkBox.Checked
Case True
resultstring = String.Format(resultstring, chkBox.Tag, "taken")
Case False
resultstring = String.Format(resultstring, chkBox.Tag, "available")
End Select
' Display it
MsgBox(resultstring)
End Sub
Private Sub FindButton_Clicked(sender As Object, e As EventArgs)
Try
' Get the checkbox and return it's name
MsgBox(GetCheckBox(CInt(Me.NumericUpDown1.Value)).Name.ToString)
Catch ex As Exception
' Display the error
MsgBox(ex.Message)
End Try
End Sub
End Class