Looping though elements in vb.net - vb.net

Is there a way I can loop though multiple elements with number based names, changing their properties?
Example:
Here are an example set of elements on my form:
Element1
Element2
Element3
Element4
Element5
This is the kind of thing i was thinking of:
For i = 1 To 5
Element + i .BackColor = Color.Maroon
Next
This is just because I have a large number of elements, which i would like to change the properties of during the application running.
Thanks for any answers.

Sure, replace Me.Controls with another control collection if that is not the right one.
Label example:
For i = 1 To 5
Dim lb = TryCast(GameInterface.Controls("Element" & i.ToString), Label)
If lb IsNot Nothing Then lb.BackColor = Color.Maroon
Next

If it is for labels on form then try this:
replace parent with Parent control
Private Sub SetControls()
Dim xControl As Control
For Each xControl parent.Controls
If (TypeOf xControl Is Label ) Then
xControl.backcolor= Color.Maroon
End If
Next xControl
End Sub

Related

vb.net find textbox name that begins with specified string in a TabControl

I have a TabControl in a form with 4 tabpages. Each tabpage has multiple GroupBox. Each GroupBox has tableLayoutPanel. Each tableLayoutPanel has pragmatically generated array of textbox. if checkbox in a tableLayoutPanel is checked by the user then textboxes in the respective row will be generated. Suppose, the name of one of my textbox array is txtMax(0), txtMax(1).......upto txtMax(42). I need to know how many txtMax(?) (along with their index array) has been generated and become visible. I have tried the the following:
Dim coutGene as integer = 0
Dim coutParameter as integer = 0
Dim indx As Integer
Dim cntl1, cntl2, cntl3 As Control
For Each cnn As TabPage In tabParameters.TabPages
cntl1 = DirectCast(cnn, TabPage)
For Each c2 As Control In cntl1.Controls
If TypeOf (c2) Is GroupBox Then
cntl2 = DirectCast(c2, GroupBox)
For Each c3 As Control In cntl2.Controls
If TypeOf (c3) Is TableLayoutPanel Then
cntl3 = DirectCast(c3, TableLayoutPanel)
For Each c4 As Control In cntl3.Controls
If TypeOf (c4) Is TextBox Then
Dim txt As TextBox = DirectCast(c4, TextBox)
If txt.Name.StartsWith("txtMax") Then
If txt.Visible = True Then
indx = CInt(Between(txt.Name, "(", ")"))
countGene = CInt(countGene + Val(txtGene(indx).Text))
countParameter = countParameter + 1
txtMax(indx).Tag = ""
End If
End If
End If
Next
End If
Next
End If
Next
Next
Function Between(value As String, a As String, b As String) As String
' Get positions for both string arguments.
Dim posA As Integer = value.IndexOf(a)
Dim posB As Integer = value.LastIndexOf(b)
If posA = -1 Then
Return ""
End If
If posB = -1 Then
Return ""
End If
Dim adjustedPosA As Integer = posA + a.Length
If adjustedPosA >= posB Then
Return ""
End If
' Get the substring between the two positions.
Return value.Substring(adjustedPosA, posB - adjustedPosA)
End Function
But the every time code is not getting inside the loop for this condition If txt.Name.StartsWith("txtMax") Then
I am stuck up here. Any assistance will be highly appreciated. Regards. Tariq
You should simplify that code to this:
For Each tp As TabPage In tabParameters.TabPages
For Each gb In tp.Controls.OfType(Of GroupBox)()
For Each tlp In gb.Controls.OfType(Of TableLayoutPanel)()
For Each tb In tlp.Controls.OfType(Of TextBox)().Where(Function(c) c.Visible AndAlso c.Name.StartsWith("txtMax"))
'If you get here, tb is definitely a visible TextBox with a Name starting with "txtMax".
Next
Next
Next
Next
That code will find every visible TextBox with a Name that starts with ""txtMax" inside a TableLayoutPanel, inside a GroupBox, inside a TabPage, inside tabParameters, guaranteed. If that code doesn;t find any such controls, it's because there are no such controls, so that's what you need to investigate.
Thank you for all yours guidelines and suggestion. I tried to implement all,,, but the code could not find the control even though the control exists and visible. I tried this simple code
For k = 1 To 42
If txtMax(k).Visible = True Then
countGene = CInt(countGene + Val(txtGene(k).Text))
countParameter = countParameter + 1
txtMax(k).Tag = ""
End If
Next
But i find that, it search and count the control that exists only in the present tabpage of the TabControl. So i modified the code, though not efficient code, to solve my problem.
I have 4 tabpages in the TabControl. So i tried to select each tabpage by its index and searched 4 times.
For tp As Integer = 0 To 3
tabParameters.SelectedIndex = tp
For k = 1 To 42
If txtMax(k).Visible = True Then
countGene = CInt(countGene + Val(txtGene(k).Text))
countParameter = countParameter + 1
txtMax(k).Tag = ""
End If
Next
Next
Though i solved my problem, but still i seek your advise for efficient code.

Accessing buttons names using variables

In visual basic I want to be able to access a button's name using the number stored in a variable.
For example if I have 24 buttons that are all named 'Button' with the numbers 1, 2, 3... 22, 23, 24 after it. If I want to then change the text in the first eight buttons how would I do that.
Here's my example to help show what I mean:
For i = 1 to 8
Button(i).text = "Hello"
Next
The proposed solutions so far will fail if the Buttons are not directly contained by the Form itself. What if they are in a different container? You could simple change "Me" to "Panel1", for instance, but that doesn't help if the Buttons are spread across multiple containers.
To make it work, regardless of the Buttons locations, use the Controls.Find() method with the "searchAllChildren" option:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ctlName As String
Dim matches() As Control
For i As Integer = 1 To 8
ctlName = "Button" & i
matches = Me.Controls.Find(ctlName, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
Dim btn As Button = DirectCast(matches(0), Button)
btn.Text = "Hello #" & i
End If
Next
End Sub
For index As Integer = 1 To 8
CType(Me.Controls("Button" & index.ToString().Trim()),Button).Text = "Hello"
Next
Use LINQ and you're good to go:
Dim yourButtonArray = yourForm.Controls.OfType(of Button).ToArray
' takes all controls whose Type is Button
For each button in yourButtonArray.Take(8)
button.Text = "Hello"
Next
Or
Dim yourButtonArray = yourForm.Controls.Cast(of Control).Where(
Function(b) b.Name.StartsWith("Button")
).ToArray
' takes all controls whose name starts with "Button" regardless of its type
For each button in yourButtonArray.Take(8)
button.Text = "Hello"
Next
In any case, .Take(8) will iterate on the first 8 items stored inside yourButtonArray

Is it possible to use Findcomponet method in vb.net?

There are seven combo box on form
I want to add the item in each combo box. But i don't want to manual mode for add the item.
I want to use the ForLoop to add the item.
I try like this, but second line is get exception occurred.
Dim cmb_Temp as ComboBox = New ComboBox
cmb_Temp.Name = "cmb_a" + "7" <- exception
so, I don't know about how to handling the ForLoop to add the item.
is it impossible in vb.net?.
is it use the FindeComponet method?
Assuming WinForms, you can use Controls.Find() like this:
Dim matches() As Control
For i As Integer = 1 To 7
matches = Me.Controls.Find("cmb_a" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is ComboBox Then
Dim cb As ComboBox = DirectCast(matches(0), ComboBox)
cb.Items.Add("SomeItem")
End If
Next

Using loop for to shorten object name in VB.NET code

i have 5 textbox and i want to call its name with for loop , how to do this :
textbox1.backcolor = color.Lightblue
textbox2.backcolor = color.Lightblue
textbox3.backcolor = color.Lightblue
textbox4.backcolor = color.Lightblue
textbox5.backcolor = color.Lightblue
i want to know how to make the code shorter with loop for, so far my only clue is this code :
Public Sub ShortCode
For i = 1 to 5
textbox(i).backcolor = color.lightblue
Next
End Sub
any idea how to make this happen ?
Assuming you stick to your naming convention, you don't need to add the text boxes to an array. Use Control.Controls. This function finds controls directly inside some container i.e. Me.Controls searches only the form (Me), not inside containers such as panels and group boxes.
For i = 1 to 5
CType(Me.Controls("textbox" & i.ToString()), TextBox).BackColor = Color.LightBlue
Next
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controls(v=vs.110).aspx
Similar (not identical) solution in one line with LINQ
Me.Controls.OfType(Of Control).
Where(Function(c As Control) c.Name.StartsWith("textbox")).
ToList().ForEach(Sub(c) c.BackColor = Color.Red)
Create an array of your TextBox controls and then iterate over them as you suggested. Below is untested code adapted from http://bytes.com/topic/visual-basic-net/answers/846341-array-textbox, but should get you there.
Dim textboxes As TextBox()
textboxes = New TextBox() {TextBox1, TextBox2, TextBox3};
For i = 1 to 3
textbox(i).backcolor = color.lightblue
if the answer above doesn't work for you try this
Public Sub ShortCode
dim i = 1
for i >= 5
textbox(i).backcolor = color.lightblue
i = i + 1
Next
End Sub
Dim TextBoxBag() As TextBox
TextBoxBag = {TextBox1,TextBox2,TextBox3,TextBox4,TextBox5}
For count = 0 to Ubound(TextBoxBag)
TextBoxBag(count).BackColor = Color.LightBlue
Next

VB manipulate lots of labels inside panel

So i have like 100 labels inside a panel and i need to to change their texts.I Tried an for and i tried Tab Index like an array without success, any ideas how I can select and change properties of these labels?
Sub setCartela(ByVal numeros As Integer)
For cont As Integer = 0 To numeros Step 1
//change labels text inside panel
Next
End Sub
Try like this ...
Dim i as Integer = 1
For Each ctrl As Control In Panel1.Controls
If ctrl.GetType.ToString = "System.Windows.Forms.Label" Then
ctrl.Text = "Text" & format(i)
End If
i += 1
Next
try this code :
dim _countLbl as integer = 1
For each Lbl as Label in Panel1.Controls.Oftype(Of Label)()
Lbl.text="Label" & _countLbl
_countLbl += 1
Next