I wan't to create a bunch of variables inside a While, each one with different names.
Here is what i tried:
Dim asd As Integer = 1
While asd < 5
Dim picturebox +asd As New Picturebox
End While
I want that it creates the Picturebox1 Picturebox2 ... and so on, but the "asd" variable won't evaluate and the code won't work. How could you create variables with different names in a loop with Visual Studio?
What I've done in the past is something like:
For i = 0 to 5
Dim t As New PictureBox()
t.Name = "PictureBox" & i
Me.Controls.Add(t)
Next
Dim picToChange = From r in Me.Controls Where Typeof(r) Is PictureBox AndAlso r.Name = "PictureBox1" Select r
If picToChange IsNot Nothing AndAlso picToChange.Any Then
'Do Something
End If
This is a very basic example and your linq would probably be more dynamic than the one I used but you should get the idea. In this case I'm assuming that you are just putting the PictureBoxes on the form, if this isn't the case then you will need to linq through whichever collection you are adding the controls to.
Edit #1:
As far as events are concerned you will need to add the handlers manually. So your code would become:
For i = 0 to 5
Dim t As New PictureBox()
t.Name = "PictureBox" & i
AddHandler t.Click, AddressOf(FunctionToHandleClick)
Me.Controls.Add(t)
Next
Dim picToChange = From r in Me.Controls Where Typeof(r) Is PictureBox AndAlso r.Name = "PictureBox1" Select r
If picToChange IsNot Nothing AndAlso picToChange.Any Then
'Do Something
End If
And the FunctionToHandleClick would look like this:
Private Sub FunctionToHandleClick(ByVal sender As Object, ByVal e As ClickEventArgs)
End Sub
Why don't you use an Array?
Dim pictureboxes(5) As PictureBox
For i As Integer = 0 To 5
pictureboxes(i) = New PictureBox()
Next
Related
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
im coding a sequence guesser game and id like to program it so whenever you enter a number wrong it resets all the labels how would i universally select the label type and make the text = Nothing
i tried this but it didnt work
Thanks
Imports System.Media
Public Class comboForm
Dim score As Integer = 0
Dim winsound As New SoundPlayer(My.Resources.winsound_wav)
' 1 7 8 8 4 7 1 5 5
Private Sub btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click
If score = 0 Then
score += 1
lblStage1.Text = "1"
ElseIf score = 7 Then
score += 1
lblStage7.Text = "7"
Else
score = 0
For Each lbl In tlpMain.Controls.OfType(Of Label)()
lbl.Text = Nothing
Next
End If
End Sub
End Class
For Each lbl In Me.Controls.OfType(Of Label)()
'...
Next
The OfType method is basically a filter by type on a list. That code is pretty much the equivalent of this:
For Each ctrl In Me.Controls
If TypeOf ctrl Is Label Then
Dim lbl = DirectCast(ctrl, Label)
'...
End If
Next
or this:
For Each ctrl In Me.Controls
Dim lbl = TryCast(ctrl, Label)
If lbl IsNot Nothing Then
'...
End If
Next
Obviously this code will only access Labels directly on the form, because it uses the form's Controls collection. Use the Controls collection of the appropriate container, e.g. a Panel to access controls in that container.
I have this code:
Dim val1,val2,val3,val4,val5, ... ,val20 As String
If Combobox1.SelectedIndex = 0 Then
val1=">"
else
val1="<"
end if
If Combobox2.SelectedIndex = 0 Then
val2=">"
else
val2="<"
end if
How can I loop this? There are 20 Combo boxes. Please help! Thanks
To loop through the controls on the form, use Me.Controls. And to check the type of the control, use Control.GetType.Name.
The problem is that separate variables like val1,val2,val3...etc cannot be easily used in a loop, so I recommend changing them to a list.
Dim val As New List(Of String)
For Each MyControl In Me.Controls
If MyControl.GetType.Name = "ComboBox" Then
Dim MyComboBox As ComboBox = CType(MyControl, ComboBox)
If MyComboBox.SelectedIndex = 0 Then
val.Add(">")
Else
val.Add("<")
end if
End If
Next
So, here are some looping sequences for you. disclaimer - code is not tested, could be bugs but logical layout should be correct
Private _numOfControls As Integer = 20
Private _variables As New Dictionary(Of String, String)(_numOfControls)
Private Sub Setup()
For i as integer = 1 To _numOfControls
Dim cboName As String = "cbo" & i
Dim cbo As New ComboBox()
cbo.Name = cboName
cbo.SelectedIndex = 0
' Add cbo location according to your logic here
container.Controls.Add(cbo) ' container - any control or form that hosts cbo
_variables.Add(cboName, ">")
AddHandler cbo.SelectedIndexChanged, AddressOf OnCboSelectedIndexChanged
Next
End Sub
' If you do this way, your control-related variable will have appropriate equality sign without need for iteration
Private Sub OnCboSelectedIndexChanged (sender As Object, e As EventArgs)
Dim cbo As ComboBox = CType(sender, ComboBox)
myDict(cbo.Name) = If(cbo.SelectedIndex = 0, ">", "<")
End Sub
' But if you do not want to do in the above^^ way, you can iterate dictionary
Private Sub FromDictionaryToCbo()
' Here you can't use for-loop on dictionary because your dictionary will be mutating. So lets iterate keys
For Each k As String In _variables.Keys.ToArray())
_variables(k) = If(CType(container.Find(k, True), ComboBox).SelectedIndex = 0, ">", "<")
Next
End Sub
' And iterating combo boxes would be something similar as another answer here
' But we use our naming convention to bypass other controls
Private Sub FromCboToDictionary()
Dim c As Control
For i As Integer = 1 To < _numOfControls
Dim key As String = "cbo" & i.ToString()
'We don't know, may be there some other combo boxes are there, so we use our naming convention instead of control type
c = container.Find(key, True)
If c IsNot Nothing Then
_variables(key) = If(CType(c, ComboBox).SelectedIndex = 0, ">", "<")
end If
Next
End Sub
Let's say I want to set the property of every item in a list like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim test As New List(Of PictureBox)
For q = 1 To 25
Dim picbox As New PictureBox
test.Add(picbox)
Next
timer tick
test.Item(everything in list).Top -= 3
End Sub
Can I do it all at once instead of iterating and setting each value separately?
You should just update the color before adding it to your list:
For q = 1 To 25
picBox.BackColor = Color.AliceBlue
test.Add(picbox)
Next
As an aside, do you realize that you are adding the same item 25 times? If you want different instances you'd need to create a new one in your loop:
For q = 1 To 25
picBox = New PictureBox
picBox.BackColor = Color.AliceBlue
test.Add(picbox)
Next
Just for fun, you could rewrite your entire snippet like so to get a list of 25 PictureBoxes:
Dim test = Enumerable.Range(1,25) _
.Select(Function(i) New PictureBox With {.BackColor = Color.AliceBlue}) _
.ToList
I'm trying to cycle through the controls on a page that consists of textboxes and a dropdown and clear them.
When I debug, parent is the current page, value is equal to ASP.nameOfCurrentpage_aspx and
Type is equal to system.web.ui.page, but c has the value of ASP.site_master and type of system.web.ui.control. I also put in x to see how many controls it finds and x comes back as 1 even though there are 15 or so textboxes on the page. Is there a way I can force c to have the value of ASP.nameOfCurrentpage_aspx? Or is that not my problem? Any help is appreciated.
Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
ClearForm(Page)
End Sub
Public Sub ClearForm(ByRef Parent As Control)
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In Parent.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
End If
Next
End Sub
The HTMLForm Control is probably nested, likely under a MasterPage. Either go fully recursive with your function or add a clause in your If Statement that looks for the Master Page. This is where breakpoints and the Watch Window are gold.
Ex:
ElseIf c.GetType.ToString = "ASP.MasterPageName_Master" Then
ClearForm(c)
Thank you every for your help. I didn't try all of the answers but I used them for ideas. This is what we came up with at work and it finds and clears all the controls on the page. We had to find the content place holder linked to the master site (cph). Again thanks for all the suggestions.
Public Sub ClearForm(ByRef Parent As Control)
Dim cph As System.Web.UI.WebControls.ContentPlaceHolder = Master.FindControl("MainBody")
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In cph.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
End If
Next
End Sub
It's been a while since I programmed anything in .NET with controls, MVC has spoiled me silly, or using VB.NET...
However I am thinking you will probably need to recurse through the stack of controls:
Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
ClearForm(Page)
End Sub
Public Sub ClearForm(ByRef Parent As Control)
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In Parent.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
ElseIf c.Controls != null ' Does VB.NET support nulls? I forget
ClearForm(c.Controls)
End If
Next
End Sub