Can I use variables to control which PictureBox I am using? - vb.net

Is there a way that I can use a variable to control which PictureBox I am using in Visual Basic?
I.e.:
CurrentNumber = 1
PictureBox(CurrentNumber).backcolour = backcolour

You can use the Me.Controls(String) indexer. It lets you specify the name (as a string) of the control you want to access, thus you can dynamically access a picture box by concatenating the string "PictureBox" with a number.
Dim TargetPictureBox As PictureBox = TryCast(Me.Controls("PictureBox" & CurrentNumber), PictureBox)
'Verifying that the control exists and that it was indeed a PictureBox.
If TargetPictureBox IsNot Nothing Then
TargetPictureBox.BackColor = Color.Red
End If
Alternatively, to save processing power by avoiding looping through the entire control collection every time you can call the OfType() extension on Me.Controls, storing the result in an array sorted by the controls' names. That way it'd only have to iterate the control collection once.
'Class level - outside any methods (subs or functions).
Dim PictureBoxes As PictureBox() = Nothing
'Doesn't necessarily have to be done in a button, it's just an example.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If PictureBoxes Is Nothing Then
PictureBoxes = Me.Controls.OfType(Of PictureBox).OrderBy(Function(p As PictureBox) p.Name).ToArray()
End If
'NOTE: CurrentNumber - 1 is necessary when using an array!
PictureBoxes(CurrentNumber - 1).BackColor = Color.Red
End Sub
NOTE: This solution will only work properly if all your picture boxes are named "PictureBox1", "PictureBox2", etc. If you suddenly skip a number ("PictureBox3", "PictureBox5", "PictureBox6") then PictureBoxes(CurrentNumber - 1) for CurrentNumber = 5 would return PictureBox6 rather than PictureBox5.

What you really should do is create a PictureBox() and use that to reference your picture boxes via an index.
The best way to build your array is to create a method that builds the array from the references created by the designer. This lets you continue to use the designer to create your controls and it makes your code check for deleted controls at design-time. Using Me.Controls(...) suffers from run-time errors if controls you are looking for have been deleted.
Here's the code you need:
Private _PictureBoxes As PictureBox() = Nothing
Sub AssignPictureBoxesArray
_PictureBoxes = {PictureBox1, PictureBox2, PictureBox3}
End Sub
Then you access them like this:
Sub SomeMethod
Dim CurrentNumber = 1
Dim PictureBox = _PictureBoxes(CurrentNumber - 1)
PictureBox.BackColor = System.Drawing.Color.Red
End Sub

Related

How can I use a variable to reference a textbox?

I'm new to visual basic and programming in general, but I'm trying to make a statistic counter sort of program. I'm trying to use a variable to reference a textbox, for example, k_kills(i) = txtKills(i).Text. This doesn't work, however, so I then tried the following:
For i = 0 To 8
Dim tempBox As TextBox
Dim tempName As String = "txtKills" & i.ToString
tempBox = Me.Controls.Item(tempName)
k_kills(i) = tempBox.Text
Next
This also doesn't work and spits out an error each time saying that 'tempBox was Nothing'.
Can anyone tell me if I can make this work?
Thanks.
You will need to find the control in some collection. By default the control would exist in its parent's Controls property and since you're trying to get the control by its name then you could use ControlCollection's Find method. If you can guarantee that the control's parent is the Form then you'd call:
Dim tempBox As TextBox = DirectCast(Me.Controls.Find(tempName, False), TextBox)
But if there is the possibility that the control's parent is something other than the Form then you'd call:
Dim tempBox As TextBox = DirectCast(Me.Controls.Find(tempName, True), TextBox)
The first would execute slightly quicker because it only iterates over the current ControlCollection whereas the second could take longer because if it cannot find the control in the current ControlCollection then it starts to iterate over the child controls as well.
Assuming the controls are all in Form as parent and they all start with txtKills...
If you are going to use these text boxes as a group for several actions you may want to build an array or list of TextBox.
Dim Kills(7) As TextBox
Private Sub CreateTextBoxArray()
Dim index As Integer
For Each ctrl As Control In Controls
If ctrl.Name.StartsWith("txtKills") Then
Kills(index) = DirectCast(ctrl, TextBox)
index += 1
End If
Next
End Sub
Private Sub ClearKillTextBoxes()
For Each t In Kills
t.Clear()
Next
End Sub
Private Function GetTextFromKillBoxes() As List(Of String)
Dim lst As New List(Of String)
For Each t In Kills
lst.Add(t.Text)
Next
Return lst
End Function
After Mary's comment I edit my answer to add this line --> My code does not work if Option Strict is On and 'For' starting in 0 or 1 or any number and txtKills[X] exists.
This was my previous answer and I don't know if I have to delete or not:
Your code works fine but I think you have an error because your For starts in 0 and you don't have any "txtKills0". I've tested it now:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim k_kills(10) As String '<< Ignore the length
For i = 1 To 7
Dim tempBox As TextBox
Dim tempName As String = "txtKills" & i.ToString
tempBox = Me.Controls.Item(tempName)
k_kills(i) = tempBox.Text
MsgBox(k_kills(i))
Next
End Sub

Working with too many PictureBoxes, any way to use a For?

Warning : Im completely new to VB.net and only know the most basic form of programming, maybe even less
Visual Basic 2010 Express
I have declared an Array Equipa(x,y) as integer.
I have 30 PictureBoxes ( PictureBox1 to PictureBox30)
In my mind, I assigned each PictureBox to a X and Y in the Array.
At load form, I want to change the image of PictureBox5 to PictureBox25.
For this I copy pasted 20 times PictureBox(x).Image = My.Resources.GreyHexagon
I would like to have a Loop that can do this without me copy pasting so much.
During the program, clicking on PictureBox5, for example, changes it to a different image, depending on the value, of the Array declared.
If Equipa(0, 0) = 0 Then
PictureBox4.Image = My.Resources.GreyHexagon
ElseIf Equipa(0, 0) = 1 Then
PictureBox4.Image = My.Resources.BlueHexagon
Else
PictureBox4.Image = My.Resources.RedHexagon
End If
The problem, again, is I have to repeat this code, for every Array position, since each PictureBox is assigned to each position.
So what I need is a Loop that can go through each PictureBox, I'm not asking you to make that code, I just don't know how to go through each PictureBox, for example PictureBox5 to PictureBox25.
PS . The following code changes EVERY PictureBox to the Image I wan't. But I do not understand any of this code, therefor can't change it to only go through PictureBox5 to PictureBox25.
Me.SuspendLayout()
For Each box As PictureBox In Me.Controls.OfType(Of PictureBox)()
box.Image = My.Resources.RedHexagon2
Next box
Me.ResumeLayout()
What I tried once before: In the declarations,
Dim pic(29) As PictureBox
And then in Public Sub New, I wrote picarray() and then made a Private Sub picarray. In this sub I dimmed each picture to the array
pic(0) = picturebox1
pic(1) = picturebox2
pic(2) = picturebox3
...
pic(29) = picturebox30
In my case, I wanted to move all 30 at once, and I had a timer, so I did:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer1.Tick
For i = 0 To 29
pic(i).Left = pic(i).Left + 3
Next
End Sub
To move them all to the right at once. I used the same way to move them back if the last one on the left hits the form's edge.
Me.SuspendLayout()
For Each box As PictureBox In Me.Controls.OfType(Of PictureBox)()
box.Image = SomeNewPicture
Next box
Me.ResumeLayout()
If you want to be able to look at specific images, you can still just say things like PictureBox4.Image = SomeNewImage. But if you really want to access them by index, first define this variable as a member of the form class:
Private PictureBoxes() As PictureBox
And then do this in your form's Load event:
PictureBoxes = Me.Controls.OfType(Of PictureBox)().ToArray()
Now you can reference each PictureBox by index:
PictureBoxes(4).Image = SomeNewPicture
PictureBoxes(10).Image = SomeOtherNewPicture
You could also do something like this:
Me.SuspendLayout()
For i As Integer = 5 to 25
PicturesBoxes(i) = My.Resources.RedHexagon2
Next i
Me.ResumeLayout()
Finally, to address the If/Then code in your edited question, I'd do something like this:
'Note this Array shorthand requires a more recent version of Visual Studio
' I used it for brevity in the response. You should be able to convert it on your own
Dim Images() As Image = {My.Resources.GreyHexagon, My.Resources.BlueHexagon, My.Resources.RedHexagon}
Dim ImageIndex As Integer = Equipa(0, 0)
If ImageIndex < 0 OrElse ImageIndex > 1 Then ImageIndex = 2
PictureBox4.Image = Images(ImageIndex)

VB.NET How can I check if an image from my resources is loaded in a PictureBox?

I am trying to make a PictureBox change the image when pressed, and if pressed again it will change to the original image. How can I do that? Here is my code.
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
If (PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd) Then
PictureBox1.Image = WindowsApplication1.My.Resources.Resources._stop()
Else
PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd()
End If
End Sub
When I run it, it gives the following error:
Operator '=' is not defined for types "Image" and "Bitmap".
Well, it is the good kind of problem to have. There is a massive bear trap hidden in the My.Resources property getters, every time you use it you get a new bitmap object. That has many consequences, bitmaps are very expensive objects and calling their Dispose() method is very important to prevent your program from running out of memory. And comparing will always fail since it is new object. The difference between Image and Bitmap is just a minor problem.
It is crucial to use the bitmap object just once. Like this:
Private asd As Image = My.Resources.asd
Private _stop As Image = My.Resources._stop
Now you can correctly write this code since you are comparing objects for reference identity:
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
If PictureBox1.Image = asd Then
PictureBox1.Image = _stop
Else
PictureBox1.Image = asd
End If
End Sub
And like a good programmer you dispose the image objects when you no longer use them:
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
asd.Dispose()
_stop.Dispose()
End Sub
Also fix the code that first assigns the PictureBox1.Image property, we can't see it.
You can use the PictureBox's .Tag property to store information. For this, I will store the resource name.
If you have an array of the resource names to be used, you can get the next one (using Mod to wrap around from the last one to the first (zeroth - array indices start at zero in VB.NET) entry).
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Dim imageResourceNames = {"Image1", "Image2"}
Dim pb = DirectCast(sender, PictureBox)
Dim tag = CStr(pb.Tag)
pb.Image?.Dispose()
Dim nextImage = imageResourceNames((Array.IndexOf(imageResourceNames, tag) + 1) Mod imageResourceNames.Length)
pb.Image = DirectCast(My.Resources.ResourceManager.GetObject(nextImage), Image)
pb.Tag = nextImage
End Sub
Please change "Image1" and "Image2" as appropriate.
Array.IndexOf will return -1 if the item searched for is not in the array, but we are adding 1 to it so it will get the first item of the array (at index 0) if the .Tag has not been set.
If you had a third image, you would simply add its name into the array.
The line PictureBox1.Image?.Dispose() disposes of the resources used by the image - the ? makes it only do that if PictureBox1.Image is not Nothing.
When you first set the image of the PictureBox, remember to set its .Tag property appropriately so that it behaves as intended.
I used Dim pb = DirectCast(sender, PictureBox) so that you can simply copy-and-paste the code for a different PictureBox and there will be very little to change in the code - otherwise you would have to update the references to PictureBox1 all through it, which can be error-prone. Of course, at that point you would start thinking about refactoring it so that you are not repeating code (the "Don't repeat yourself", or DRY, principle).

Retrieving data on dynamic controls

I am using dynamically created controls and need to retrieve information about the control at runtime.
If IsLoaded <> "free" Then
flow_display.Controls.Clear()
For x As Integer = 0 To populate.Count - 1
If populate(x).parentID = 2 Then
Dim NewPicBox As PictureBox = New PictureBox
NewPicBox.Size = New System.Drawing.Size(697, 50)
NewPicBox.ImageLocation = pw_imgLink & populate(x).imageID
AddHandler NewPicBox.Click, AddressOf catWindow
flow_display.Controls.Add(NewPicBox)
End If
Next
IsLoaded = "free"
End If
End Sub
Here I create the control when the user clicks on the appropriate label. Right now the catWindow sub is empty. I need to figure out which button is clicked and figure out its location on the populate list. I have tried a few things and from what I've read from other questions can't seem to find anything the helps. Thanks :)
For finding out which PictureBox is pressed, your catWindow Sub should look like this:
Public Sub catWindow(ByVal sender As Object, ByVal e As EventArgs)
Dim box As PictureBox = TryCast(sender, PictureBox)
If box Is Nothing Then Exit Sub
'Now "box" refers to the PictureBox that was pressed
'...
End Sub
If you want to find it's location in the populate list, you will need to iterate through the list until you find the matching box. You could also pre-empt a property on your PictureBox that isn't doing anything else and use it to store the index. Older forms tools used to have a .Tag property especially for this kind of thing. But really, the need to do this smells like a design flaw to me.
FWIW, I'd rewrite your original sample like this:
If IsLoaded <> "free" Then
flow_display.SuspendLayout()
flow_display.Controls.Clear()
For Each box As PictureBox In populate
.Where(Function(p) p.parentID = 2)
.Select(Function(p) New PictureBox() With {
.Size = New System.Drawing.Size(697, 50),
.ImageLocation pw_imgLink & p.imageID })
AddHandler box.Click, AddressOf catWindow
flow_display.Controls.Add(box)
Next box
flow_display.ResumeLayout()
IsLoaded = "free"
End If

Removing a collection of controls

I have a form (Form1) and it has 30 controls.
When I hit a button, I want to remove those 30 buttons and put other controls on the form.
Now, my problem is that this is to slow.
I have this list with controls I want to delete and I run through them with a For Each.
Private Sub ClearControls()
'removing the controls from Me.Controls
For Each Control As Control In ListToDelete
Me.Controls.Remove(Control)
Next
ListToDelete = New List(Of Control)
End Sub
Now, if you watch the form, you see the controls getting deleted 1 by 1. This action takes about 0.4 seconds (timed with the build-in stopwatch) and that's too long.
Are there any solutions to delete the controls in a faster way or is it only possible to delete the controls 1 by 1?
Maybe an important fact is that everything is connected with a database.
The controls are created by a class I defined myself (TableDrawer) and it creates a rectangle or circle (depends on info from the database).
I add the selfmade controls to the form and when I want to delete them, it takes 0.4 seconds to get other controls on the form - also with information out of my database.
Hopefully this clears some things up and I hope you can help me out... It really has to go a bit faster (I hope to get 0.1s or lower)
Hiding the Panel first seems to make the controls disappear quicker than just clearing the Panel. See this code:
Option Strict On
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Panel1.Visible = False
If Not Panel1.Controls.OfType(Of Button).Any() Then
For x As Integer = 1 To 10
For y As Integer = 1 To 10
Dim btn As New Button()
btn.Size = New Size(45, 45)
btn.Location = New Point((x - 1) * 45, (y - 1) * 45)
btn.Text = (x * y).ToString()
Panel1.Controls.Add(btn)
btn.Visible = True
Next
Next
End If
Panel1.Visible = True
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Panel1.Visible = False
Panel1.Controls.Clear()
Panel1.Visible = True
End Sub
End Class
This code has 2 buttons, and a Panel. Button1 generates 100 buttons, places them on a Panel. Button2 hides the panel before removing them. Perhaps you can experiment with this idea.
It's not the deletion that tends to take the time - it's redrawing the form each time. Try surrounding your deletion code with calls to SuspendLayout and ResumeLayout
Private Sub ClearControls()
'removing the controls from Me.Controls
Me.SuspendLayout()
For Each Control As Control In ListToDelete
Me.Controls.Remove(Control)
Next
Me.ResumeLayout()
ListToDelete = New List(Of Control)
End Sub
Put the controls in a panel container control. Removing the panel container removes all child controls.
kindly never used remove and panel.removeat to remove any controls. It won't be able to delete last control in panel layout.Especially for panel.removeat will return out of index error once delete the last end control in panels. I'm also wondering need to know why this is problem appears?
Stored all the control name in string array, find those controls in panel and delete them, Try below code will help you delete all control in panel for one short. Try using with find and removeBykey function will make your task easier.
Dim ctrllist() as string
Dim counts = 0
For each control in Me.panel1.controls
redim Preserve ctrllist(0 to counts)
ctrllist(counts)=control.name
counts+=1
Next
For counts=Lbound(ctrllist) to Ubound(ctrlllist)
If me.panel1.controls.find(ctrllist(counts),True).Length>0 then
me.panel1.controls.removeBykey(ctrllist(counts))
End If
Next
Hope it will help.
Thanks user1884888! The technique helps me.
If I use Me.ScrollPanelControl.Controls.Clear() then the application goes unresponsive and there's no choice to terminate it from Task Manager but using this technique helps me.
This code is to help some one having the same problem.
While (True)
Dim count = Me.ScrollPanelControl.Controls.Count
If count <= 0 Then
Exit While
End If
Dim firstCtrl = CType(Me.ScrollPanelControl.Controls(0), MyControl)
If Not firstCtrl.IsMoving Then
If Me.ScrollPanelControl.Controls.Find(firstCtrl.Name, True).Length > 0 Then
Me.ScrollPanelControl.Controls.RemoveByKey(firstCtrl.Name)
End If
ElseIf count > 1 Then
firstCtrl = CType(Me.ScrollPanelControl.Controls(1), MyControl)
If Me.ScrollPanelControl.Controls.Find(firstCtrl.Name, True).Length > 0 Then
Me.ScrollPanelControl.Controls.RemoveByKey(firstCtrl.Name)
End If
Else
Exit While
End If
End While