Is there a way to simplify this code? Visual Basic Here - vb.net

I'm a newbie to Visual Basic and I have this code over here that's been bugging me. I can't think of another way to simplify this. Can you please help? Thanks!:
Private Sub PictureBox_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click,
PictureBox2.Click, PictureBox3.Click, PictureBox4.Click, PictureBox5.Click, PictureBox6.Click,
PictureBox7.Click, PictureBox8.Click, PictureBox9.Click, PictureBox10.Click, PictureBox11.Click,
PictureBox12.Click, PictureBox13.Click, PictureBox14.Click, PictureBox15.Click, PictureBox16.Click,
PictureBox17.Click, PictureBox18.Click, PictureBox19.Click, PictureBox20.Click, PictureBox21.Click,
PictureBox22.Click, PictureBox23.Click, PictureBox24.Click, PictureBox25.Click, PictureBox26.Click,
PictureBox27.Click, PictureBox28.Click, PictureBox29.Click, PictureBox30.Click, PictureBox31.Click,
PictureBox32.Click, PictureBox33.Click, PictureBox34.Click, PictureBox35.Click, PictureBox36.Click,
PictureBox37.Click, PictureBox38.Click, PictureBox39.Click, PictureBox40.Click, PictureBox41.Click,
PictureBox42.Click, PictureBox43.Click, PictureBox44.Click, PictureBox45.Click, PictureBox46.Click,
PictureBox47.Click, PictureBox48.Click, PictureBox49.Click, PictureBox50.Click, PictureBox51.Click,
PictureBox52.Click, PictureBox53.Click, PictureBox54.Click, PictureBox55.Click, PictureBox56.Click,
PictureBox57.Click, PictureBox58.Click, PictureBox59.Click, PictureBox60.Click, PictureBox61.Click,
PictureBox62.Click, PictureBox63.Click, PictureBox64.Click
...............
............... (stuff is down here.)
...............
...............
End Sub

You will need to store the lists in a collection of some sort. This can either be an array or a List(Of PictureBox) or if all of the controls have the same parent you can simply leverage the Controls property.
Once you have the collection in place, you will need to iterate over collection and use AddHandler to reference. Inside the referenced method, you would get the sender, and convert it to a PictureBox.
Here is an example assuming all the PictureBox controls are on the Form:
Private Sub Form1_Load(sender As Object, e As EventArgs)
For Each pb In Controls.OfType(Of PictureBox)()
AddHandler pb.Click, AddressOf pb_Click
Next
End Sub
Private Sub pb_Click(sender As Object, e As EventArgs)
Dim pb = DirectCast(sender, PictureBox)
' pb is the control that was clicked
End Sub

Here's how to build a list of the pictureboxes, with them "in order", assuming they are already on the form:
Public Class Form1
Private PBs As New List(Of PictureBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 1 To 64
Dim ctlName As String = "PictureBox" & i
Dim ctl As Control = Me.Controls.Find(ctlName, True).FirstOrDefault
If Not IsNothing(ctl) AndAlso TypeOf ctl Is PictureBox Then
Dim pb As PictureBox = DirectCast(ctl, PictureBox)
AddHandler pb.Click, AddressOf PB_Click
PBs.Add(pb)
Else
MessageBox.Show("Unable to find " & ctlName)
End If
Next
End Sub
Private Sub PB_Click(sender As Object, e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
' ... do something with pb ...
End Sub
End Class
From the comments:
Wait a minute, how do I do For Each pb In Controls.OfType(Of
PictureBox)() AddHandler pb.Click, AddressOf pb_Click Next But for a
List(Of Picturebox) named "Formula"?
For Each pb As PictureBox in Formula
AddHandler pb.Click, AddressOf pb_Click
Next
Here's what you code produces after turning on the BorderStyle:

Related

Add/modify handler in multiple ComboBoxes

I want to disable the mousewheel to prevent scrolling in the ComboBoxes.
For one ComboBox this works:
Private Sub CmbDienst_MouseWheel(sender As Object, e As MouseEventArgs) Handles CmbDienst.MouseWheel
Dim HMEA As HandledMouseEventArgs = DirectCast(e, HandledMouseEventArgs)
HMEA.Handled = True
End Sub
But how can I add this to ALL ComboBoxes? There are a lot of them in the form.
I was looking for something like
Private Sub Combo_Mouse()
For Each c As Control In Me.Controls.OfType(Of ComboBox)()
'And then...?
Next
End Sub
Thanks!
It works. The problem I had was that the comboboxes are in several containers, such as Panels and Datagridviews. Then is "me.controls, etc" not enough.
So I finally made this out of it:
In the Form load:
EnumControls(Me)
In the Programm:
Private Sub ComboBoxes_MouseWheel(sender As Object, e As MouseEventArgs)
Dim hmea = DirectCast(e, HandledMouseEventArgs)
hmea.Handled = True
End Sub
Private Sub EnumControls(ByVal ctl As Control)
If ctl.HasChildren Then
For Each c As Control In ctl.Controls
For Each comboBox In c.Controls.OfType(Of ComboBox)()
AddHandler comboBox.MouseWheel, AddressOf ComboBoxes_MouseWheel
Next
EnumControls(c)
Next
End If
End Sub
It works. Suggestions are welcome!
Try this
Private Sub buttonHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim mwe As HandledMouseEventArgs = DirectCast(e, HandledMouseEventArgs)
mwe.Handled = True
End Sub
and in FormLoad
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each c As Control In Me.Controls.OfType(Of ComboBox)()
'You cann acces to ComboBox her by c
AddHandler c.MouseWheel, AddressOf buttonHandler
Next
End Sub

Make checkbox.Checked = True whose corresponding PictureBox is clicked

I have 28 CheckBoxes in a windows form. Each box has PictureBox above it. When the user clicks on a PictureBox, I want to change the BackColor of the PictureBox to green, and make its corresponding CheckBox.Checked = True
The code I am using:
Private Sub PictureBox1_Click
PictureBox1.BackColor = Color. Green
CheckBox1.Checked = true
For 28 it will be a lengthy process. Is there any easy solution?
Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes.
Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
Next
End Sub
Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
Dim pb = CType(sender, PictureBox)
Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
pb.BackColor = Color.Green
cb.Checked = True
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
Next
End Sub
In the Load() event of your form, use Controls.Find() to get a reference to both the PictureBoxes and CheckBoxes. Store the CheckBox reference in the Tag() property of each PictureBox. Wire up the Click() event of you PB. In that event, change the color of the PB, then retrieve the CheckBox from the Tag() property and check the box as well:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 1 To 28
Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault
Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault
If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then
PB.Tag = CB
CB.Tag = PB
AddHandler PB.Click, AddressOf PB_Click
AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged
End If
Next
End Sub
Private Sub PB_Click(sender As Object, e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox)
If pb.BackColor.Equals(Color.Green) Then
pb.BackColor = Color.Empty
cb.Checked = False
Else
pb.BackColor = Color.Green
cb.Checked = True
End If
End Sub
Private Sub CB_CheckedChanged(sender As Object, e As EventArgs)
Dim cb As CheckBox = DirectCast(sender, CheckBox)
Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox)
pb.BackColor = If(cb.Checked, Color.Green, Color.Empty)
End Sub

How To Auto Refresh Xml page in VB.NET?

Trying to auto refresh xml page with timer but i see the node but the timer does not work. I post my code if you can find the problem thanks a lot in advance.
Private Sub TextBox1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dom As New Xml.XmlDocument
dom.Load("http://69.175.13.131:8050/stats")
TextBox1.Clear()
Dim monitorid As String = String.Empty
For Each node As Xml.XmlNode In dom.SelectNodes("//SHOUTCASTSERVER/SONGTITLE")
monitorid = node.InnerText
TextBox1.Text=(monitorid)
Next
Dim timer As New Timer()
timer.Interval = 20000
AddHandler timer.Tick, AddressOf TextBox1.Refresh
timer.Start()
End Sub
The Control.Refresh method is only to redraw the control, not update its contents (unless you write code in an unexpected place to do that).
If you put the code to retrieve the data in a separate method, you can make it a bit tidier and easier to see what is happening in the code. Something like:
Public Class Form1
Dim tim As Timer
Sub ShowCurrentSongTitle(sender As Object, e As EventArgs)
Dim dom As New Xml.XmlDocument
dom.Load("http://69.175.13.131:8050/stats")
Dim node As Xml.XmlNode = dom.SelectSingleNode("//SHOUTCASTSERVER/SONGTITLE")
Dim monitorid As String = node.InnerText
TextBox1.Text = monitorid
TextBox1.SelectionStart = monitorid.Length
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ShowCurrentSongTitle(Nothing, EventArgs.Empty)
tim = New Timer With {.Interval = 20000}
AddHandler tim.Tick, AddressOf ShowCurrentSongTitle
tim.Start()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
' tidy up...
RemoveHandler tim.Tick, AddressOf ShowCurrentSongTitle
End Sub
End Class

image drag and drop - how to get image

I am trying to write a program that allows the user to drag and drop an image from any folder to the form's picture box. I got the drag and drop part, but I don't know to do is how to store the image on a variable to be able to be dropped on the picturebox. Here is what I have so far:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
AddHandler picCategoryImage.DragDrop, AddressOf picCategoryImage_DragDrop
AddHandler picCategoryImage.DragEnter, AddressOf picCategoryImage_DragEnter
End Sub
Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop
Dim picbox As PictureBox = CType(sender, PictureBox)
Dim g As Graphics = picbox.CreateGraphics()
g.DrawImage(CType(e.Data.GetData(DataFormats.Bitmap), Image), New Point(0, 0))
End Sub
Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter
If e.Data.GetDataPresent(DataFormats.Bitmap) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
where am I going wrong here?
You need DataFormats.FileDrop instead of DataFormats.Bitmap in DragEnter event. And in DragDrop you open the file name you get from e.Data.GetData():
Private Sub picCategoryImage_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragDrop
Dim picbox As PictureBox = CType(sender, PictureBox)
Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
If files.Length <> 0 Then
Try
picbox.Image = Image.FromFile(files(0))
Catch ex As Exception
MessageBox.Show("Problem opening file ")
End Try
End If
End Sub
Private Sub picCategoryImage_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
You need also to set(in form load event):
picCategoryImage.AllowDrop = True

VB 2010 Form Show

i currently have multiple forms (around 30 forms) and i am switching between forms. The Main form (Form1) has 29 buttons and each button will take me to the respective form number (example: button3 = form3, button20=form20, etc).
I understand that I can use the code:
me.hide
form1.show
I want a method to pass the form name dynamically, something along the lines of:
me.controls(FormName).show
Is this possible?
Create a new project with three forms (Form1, Form2, and Form3). Put two buttons on Form1 (named Button2 and Button3), then place the following source code in Form1:
Option Strict On
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Call FormFromButton(DirectCast(sender, Button))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Call FormFromButton(DirectCast(sender, Button))
End Sub
Public Sub FormFromButton(btn As Button)
Dim i As Integer = CInt(btn.Name.Substring(6)) 'Get number after "button" (6 characters)
Dim f As Form = GetForm("Form" & i.ToString)
f.Show()
f.Activate()
End Sub
Public Function GetForm(formClassName As String) As Form
'see if it is already instanced
For Each f As Form In My.Application.OpenForms
If f.GetType.Name = formClassName Then Return f
Next f
'create new instance
Dim strFullName As String = Me.GetType.Namespace & "." & formClassName
Dim o As Object = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(strFullName)
Dim frm As Form = DirectCast(o, Form)
Return frm
End Function
End Class
Myself created 4 forms one is parent another 3(Form3,Form4,Form5) is child and i was created 3 buttons in parent form and that button Text is Form3,Form4,Form5
Imports System
Imports System.Reflection
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is Button Then
Dim btn As Button
btn = DirectCast(ctrl, Button)
AddHandler btn.Click, AddressOf Me.buttonclick
End If
Next
End Sub
Private Sub buttonclick(sender As Object, e As EventArgs)
Dim frmname As Button = DirectCast(sender, Button)
Dim frmAssembly As Assembly = Assembly.LoadFile(Application.ExecutablePath)
For Each type As Type In frmAssembly.GetTypes
If type.BaseType = GetType(Form) Then
If (type.Name = frmname.Text) Then
Dim frmshow As Form = DirectCast(frmAssembly.CreateInstance(type.ToString()), Form)
For Each frm As Form In Me.MdiChildren
frm.Close()
Next
frmshow.Show()
End If
End If
Next
End Sub
End Class
Private Sub ButtonClick(ByVal sender As Object, e As System.EventArgs)
Dim btn As Button = DirectCast(sender, Button)
Dim formname As String = "form" & btn.Name(btn.Name.Length - 1)
Dim frm As Form = GetForm(formname)
frm.Show()
End Sub
Private Function GetForm(ByVal Formname As String) As Form
Dim t As Type = Type.GetType(Formname) ', True, True)
If t Is Nothing Then
Dim Fullname As String = Application.ProductName & "." & Formname
t = Type.GetType(Fullname, True, True)
End If
Return CType(Activator.CreateInstance(t), Form)
End Function
Private Sub AddHandlers()
AddHandler Button1.Click, AddressOf ButtonClick
AddHandler Button2.Click, AddressOf ButtonClick
AddHandler Button3.Click, AddressOf ButtonClick
AddHandler Button4.Click, AddressOf ButtonClick
End Sub
Private Sub RemoveHandlers()
RemoveHandler Button1.Click, AddressOf ButtonClick
RemoveHandler Button2.Click, AddressOf ButtonClick
RemoveHandler Button3.Click, AddressOf ButtonClick
RemoveHandler Button4.Click, AddressOf ButtonClick
End Sub
Private Sub Form2_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated
AddHandlers()
End Sub
Private Sub Form2_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
RemoveHandlers()
End Sub