VB .Net Can i manage all events from inside a groupbox in an efficient way? - vb.net

I have a groupbox containing a lot of Checkboxes - only Checkboxes.
Is there a simple/fast way to handle the same event coming from different controls?
I know I can write a single sub and let it handle all the Events, but it's really time-consuming to write.
Using Visual Studio 2012

If your time concern is about writing and managing a large Handles clause, you can simply loop through the GroupBox's Controls collection upon construction of your UserControl/Form and wire up each event on each CheckBox, like so:
Imports System.Linq
Public Sub New()
InitializeComponent()
For Each chkBox As CheckBox In yourGroupBoxVariable.Controls.OfType(Of CheckBox)()
AddHandler chkBox.CheckStateChanged, AddressOf YourCheckStateChangedHandlerMethod
Next
End Sub
Private Sub YourCheckStateChangedHandlerMethod(ByVal sender As Object, ByVal e As EventArgs)
' Your handler code for the checkboxes
End Sub
This leverages LINQ's OfType Enumerable extension to filter down all child controls of the GroupBox to those of type CheckBox.

Another possibility is to create a custom GroupBox, i.e. deriving from GroupBox and exposing the event yourself:
Public Class CheckboxGroup
Inherits GroupBox
Public Event CheckboxChanged(source As CheckBox, e As EventArgs)
Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
' this method is called everytime a checkbox is added
If TypeOf e.Control Is CheckBox Then
Dim chk As CheckBox = DirectCast(e.Control, CheckBox)
AddHandler chk.CheckedChanged, AddressOf AllCheckedChange
End If
End Sub
Private Sub AllCheckedChange(source As Object, e As EventArgs)
If TypeOf source Is CheckBox Then
Dim chk As CheckBox = DirectCast(source, CheckBox)
RaiseEvent CheckboxChanged(chk, e)
End If
End Sub
End Class
You can then attach to the event in the Form like:
Private Sub CheckboxChanged(source As CheckBox, e As EventArgs) Handles gb.CheckboxChanged
MsgBox(source.Text & " to " & source.Checked)
End Sub
Advantage: you can never miss to add an event handler to a CheckBox, even if it is created dynamically.

Related

How to notice any change on a form

I have a form with many different radiobuttons, checkboxes and textboxes. Depending on their values I start my calculations. The results are shown on the same form and panel. If any of my controls (checkboxes, ...) changes, I want to immediatly update the results without a need to press any update-button.
I could define a statsChanged-sub for every single control on the form but there are so many. Isn't there a way/event of the form starting whenever a control is changed? It should be something like controlOnFormChanged. How can I get a sub that starts whenever a any control on the form changed?
Thank you in advance!
You could wire up the events that correspond to the desired change manually to a specific event handler:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Iterate through all controls and handle them according to their type
For Each c As Control In Me.Controls
If TypeOf (c) Is CheckBox Then
AddHandler CType(c, CheckBox).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is RadioButton Then
AddHandler CType(c, RadioButton).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is TextBox Then
AddHandler CType(c, TextBox).TextChanged, AddressOf SomethingChanged
ElseIf ......
......
End If
Next
End Sub
Private Sub SomethingChanged(sender As Object, e As EventArgs)
'Whatever it is you do
End Sub
End Class
Whenever one of the events on a control fires the sub SomethingChanged is called, allowing you to update your results.
Please be aware: If you have controls in subcontainers like Panels you need to modify this method and iteratively get all controls in all containers.
Here is, for example, a solution to this:
http://kon-phum.com/tutors/pascal/programming_cs_getcontrolsonform.html
Public Shared Function GetAllControls(ctrls As IList) As List(Of Control)
Dim RetCtrls As New List(Of Control)()
For Each ctl As Control In ctrls
RetCtrls.Add(ctl)
Dim SubCtrls As List(Of Control) = GetAllControls(ctl.Controls)
RetCtrls.AddRange(SubCtrls)
Next
Return RetCtrls
End Function

How can I change the CheckChanged when clicking the same object in VB 2010?

I want to know if it is possible in VB 2010 to changed the CheckChanged of a CheckBox when clicking the same object. For Example:
I have a 1 picturebox named pic1 and a checkbox named chck1, If I click the pic1, the chck1 must be checked but If I click again the pic1, chck1 must be unchecked and I click again the pic1, chck1 must be check again and so on..
I really don't have an idea if it is working or impossible in VB 2010, I hope someone can help me. Thank you very much.
If it's a WinForm, then you just have to implement something like this:
you have your PictureBox and your Checkbox, and you just have to add a clickhandler to your picturebox like this:
private void pictureBox1_Click(object sender, EventArgs e)
{
checkBox1.Checked = !checkBox1.Checked;
}
This Method always negates the Checked-State of the Checkbox (it's way simpler than a if/else)
checkbox1.Checked contains the checked-state, so that is how you can uncheck/check it.
Edit: i did it in c#, sorry,
in VB.NET it would be something like
Private Sub pictureBox1_Click(sender As Object, e As EventArgs)
checkBox1.Checked = Not checkBox1.Checked;
End Sub
In a WinForms application just add the event handler for the click event of your PictureBox.
You could that easily with the Form Designer or, if using code, then write
' In the form constructor
Public Sub Form1()
' First initialize your form controls'
InitializeComponent()
' then add the event handler for the picturebox click event'
AddHandler pic1.Click, AddressOf pic1_Click
End Sub
Private Sub pic1_Click(sender As Object, e As EventArgs)
' toogle the checked state of the checkbox'
chk1.Checked = Not chk1.Checked
End Sub
As said below from Mr Neolisk you could also shorten this code simply adding the Handles clause to the pic1_Click event thus removing the code in the Form constructor
Private Sub pic1_Click(sender As Object, e As EventArgs) Handles pic1.Click
' toogle the checked state of the checkbox'
chk1.Checked = Not chk1.Checked
End Sub

trigger an event from another control

I'm using vb.net and winform. I am coming across an issue which I'm pounding my head against for the past few hours.
I have a main usercontrol which I added a groupbox and inside that groupbox, added a control like this:
main usercontrol
Me.GroupBox1.Controls.Add(Me.ctlWithDropDown)
user control ctlWithDropDown
Me.Controls.Add(Me.ddList)
Private Sub ddlList_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlList.SelectionChanged
'some simple logic here to check if value changed
End Sub
The main usercontrol inherits the base class which has an event to set a value to true or false like so:
Public Event SetFlag(ByVal value As Boolean)
I want to know how I can trigger/set this boolean value from the dropdownlist when the SelectionChanged event is trigger. Any help on this issue?
Wire up an event handler for the drop down list:
AddHandler Me.ctlDropDown.SelectedIndexChanged, AddressOf ddlSelectedIndexChanged
Me.GroupBox1.Controls.Add(Me.ctlDropDown)
Make sure you create ddlSelectedIndexChanged in your control and have it fire the SetFlag Event:
Protected Sub ddlSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent SetFlag(True)
End Sub
I presume the me.ctlDropDown is something that you are making programmatically? If so then this sort of thing should work for you.
Public Sub Blah()
Dim ctlDropDown As New ComboBox
AddHandler ctlDropDown.SelectedIndexChanged, AddressOf IndexChangedHandler
Me.GroupBox1.Controls.Add(ctlDropDown)
End Sub
Private Sub IndexChangedHandler()
'Do whatever you need here.
End Sub
However, if this is not created at runtime should make an event handler like:
Private Sub IndexChangedHandler() Handles Me.ctlDropdown.SelectedIndexChanged
'Do whatever you need here.
End Sub

Raising events from a List(Of T) in VB.NET

I've ported a large VB6 to VB.NET project and while it will compile correctly, I've had to comment out most of the event handlers as to get around there being no array collection for winform objects and so putting the various objects that were in at the collection array into a List object.
For example, in VB6 you could have an array of Buttons. In my code I've got
Dim WithEvents cmdButtons As New List(Of Button)
(and in the Load event, the List is propagated)
Obviously, you can't fire an event on a container. Is there though a way to fire the events from the contents of the container (which will have different names)?
In the Button creation code, the event name is there, but from what I understand the handler won't intercept as the Handles part of the code is not there (commented out).
I'm not exactly sure what you're after, but if you want to be able to add event handlers to some buttons in a container and also have those buttons referenced in a List, you can do something like
Public Class Form1
Dim myButtons As List(Of Button)
Private Sub AddButtonsToList(targetContainer As Control)
myButtons = New List(Of Button)
For Each c In targetContainer.Controls
If TypeOf c Is Button Then
Dim bn = DirectCast(c, Button)
AddHandler bn.Click, AddressOf SomeButton_Click
myButtons.Add(bn)
End If
Next
End Sub
Private Sub SomeButton_Click(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
MsgBox("You clicked " & bn.Name)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' GroupBox1 has some Buttons in it
AddButtonsToList(GroupBox1)
End Sub
End Class

Handling all textbox event in one Handler

I do know how to handle event of textboxes in my form. But want to make this code shorter because I will 30 textboxes. It's inefficient to use this:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged, TextBox8.TextChanged, TextBox9.TextChanged, TextBox10.TextChanged
Dim tb As TextBox = CType(sender, TextBox)
Select Case tb.Name
Case "TextBox1"
MsgBox(tb.Text)
Case "TextBox2"
MsgBox(tb.Text)
End Select
End Sub
Is there a way to shorten the handler?
You can use Controls.OfType + AddHandler programmatically. For example:
Dim textBoxes = Me.Controls.OfType(Of TextBox)()
For Each txt In textBoxes
AddHandler txt.TextChanged, AddressOf txtTextChanged
Next
one handler for all:
Private Sub txtTextChanged(sender As Object, e As EventArgs)
Dim txt = DirectCast(sender, TextBox)
Select Case txt.Name
Case "TextBox1"
MsgBox(txt.Text)
Case "TextBox2"
MsgBox(txt.Text)
End Select
End Sub
If you have created very Textbox with the Designer, I don't think there is a better method.
But, if you have created the Textboxes dynamically, you should AddHandler in this way:
For i = 0 to 30
Dim TB as New Texbox
AddHandler TB.TextChanged, TextBox1_TextChanged
'Set every Property that you need
Me.Controls.Add(TB)
Next
Say If you are having that 30 textboxes inside a panel(PnlTextBoxes), Now you can create handler for your textboxes dynamically like this below
For each ctrl in PnlTextBoxes.controls
If TypeOf ctrl is TextBox then
AddHandler ctrl.TextChanged, AddressOf CommonClickHandler
end if
Next
Private Sub CommonHandler(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
MsgBox(ctype(sender,TextBox).Text)
End Sub
The best way would be to inherit from TextBox, override its OnTextChanged method to add your custom handling code, and then use that on your form(s) instead of the built-in TextBox control.
That way, all of the event handling code is in one single place and you increase abstraction. The behavior follows and is defined within the control class itself, not the form that contains the control. And of course, it frees you from having a bunch of ugly, hard-to-maintain Handles statements, or worse, slow and even uglier For loops.
For example, add this code defining a new custom text box control to a new file in your project:
Public Class CustomTextBox : Inherits TextBox
Protected Overridable Sub OnTextChanged(e As EventArgs)
' Do whatever you want to do here...
MsgBox(Me.Text)
' Call the base class implementation for default behavior.
' (If you don't call this, the TextChanged event will never be raised!)
MyBase.OnTextChanged(e)
End Sub
End Class
Then, after you recompile, you should be able to replace your existing TextBox controls with the newly-defined CustomTextBox control that has all of your behavior built in.