Get the name of controls (buttons) dynamically - vb.net

I have 10 buttons namely button01, button02 ... button10. What I want is how to manipulate it.
For x=1 to 10
button(x).text = "blah" 'from database...or something
next
I need to do this because I have 10 buttons or more and I want to manipulate it through initialization. So that I don't do it manually one by one. I don't know how to do this. I'm still new in .NET.

You should not need to do it in this error-prone way just to save you some lines of code. But if you really want....
You can use a Panel or another container control that groups the related controls logically. Then use MyPanel.Controls.OfType(Of Button)() to filter and find all the buttons there.
For Each btn As Button In MyPanel.Controls.OfType(Of Button)()
btn.Text = "blah" 'from database...or something
Next
Another way is to put them all in an array or other collection type like List(Of Button) first and loop over them afterwards:
Dim myButtons = {button1, button2, button3, button4, button5, button6}
For Each btn In myButtons
btn.Text = "blah" 'from database...or something
Next
Last you could use ControlCollection.Find to find controls with a given string for its name:
For i As Int32 = 1 To 10
Dim btns = Me.Controls.Find("button" & i, True)
If btns.Length > 0 Then
btns(0).Text = "blah" 'from database...or something
End If
Next

Simply:
For i As Integer = 1 To 10
Me.Controls("button" & i.ToString("00")).Text = "blah"
Next

You have to iterate through the parent container of these buttons.
Say you are holding these controls inside a panel called PnlTest, then you have to do it like this:
For Each xControls As Control In PnlTest.Controls
If TypeOf xControls Is Button Then
xControls.Text = "blah" 'from database...or something
End If
Next

You could try using the method FindControl as such from the WebControl:
For x=1 to 10
FindControl("button" & if(x < 10, "0" & x, x) = "blah" 'from database...or something
next
EDIT: I primarily use C#, not VB, so it may need some alteration. However, the approach is the same I would believe.

zeroyevi cubosoft.cl -- DevExpress -- la clave esta (bar.button.item) en Me.RibbonControl.Items("NAME_BUTTON" ).Enabled = True or false
Private Sub GetSearchPerfilModulosBotones(ByVal _id_perfil As String)
Dim dt As New DataTable
Dim _act_btns As Boolean
Dim _name_btns As String
Dim _name_module As String = Me.Name.ToString()
Try
Dim _ControlDatosSistema As New ControlDatosSistema()
With _ControlDatosSistema
dt = .GetSearchPerfilModulosBotones(_id_perfil, _name_module )'SQL QUERY
If (dt.Rows.Count >= 1) Then
For Each row As DataRow In dt.Rows
_act_btns = row("ACT_BTNS") 'BOTONES PERFIL True or False
_name_btns = row("NAME_BTNS").ToString()'NOMBRE BOTONES TABLA
Me.RibbonControl.Items(_name_btns ).Enabled = _act_btns
Next
End If
End With
_ControlDatosSistema = Nothing
dt.Dispose()
Catch ex As Exception
End Try
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.

Setting a VBA form object using a string

Hello,
I am trying to set up a form which is a calendar from which the user can select a date (by default the current month appears). The form consists of 42 command buttons (I have left the default name ie. CommandButton1) which I am setting the day number.
At the moment I have a long-winded section of code for each button (I used Excel to generate this rather than type it all out) which locks and hides the button if it is outside of the month in question which looks like this:
NewDate.CommandButton1.Caption = Format(DATlngFirstMonth - DATintDayNumFirst + DATintX, "dd")
If DATintX < DATintDayNumFirst Then
With NewDate.CommandButton1
.Locked = True
.Visible = DATbooShowExtraDays
.ForeColor = RGB(150, 150, 150)
End With
Else
With NewDate.CommandButton1
.Locked = False
.Visible = True
.ForeColor = RGB(0, 0, 0)
End With
End If
I know that I can refer to a command button by:
Dim objCommandButton As Object
Set objCommandButton = NewDate.CommandButton1
..which neatens the code up somewhat. But what I would like to do is refer to the command button as a string so I can loop through all 42, ie.
Dim n as integer
n = 1
Do Until n > 42
Set objCommandButton = NewDate.CommandButton & n
'Some operations
n = n + 1
Loop
Many thanks in advance for assistance.
You can loop through all controls of the form. Try
Sub LoopButtons()
Dim it As Object
For Each it In NewDate.Controls
Debug.Print it.Name
Next it
End Sub
Then you can put conditional expression (if ... then) in place of Debug.Print or whatever. For example
If Instr(it.Name, "CommandButton") Then
'do your code
end if
Here's code which iterates over ActiveX controls on active sheet:
Sub IterateOverActiveXControlsByName()
Dim x As Integer
Dim oleObjs As OLEObjects
Dim ctrl As MSForms.CommandButton
Set oleObjs = ActiveSheet.OLEObjects
For x = 1 To 10
Set ctrl = oleObjs("CommandButton" & x).Object
Next
End Sub

VB.Net Loop controls by names using variables

I need to set text of some controls.
I have a Form with some CheckBoxes an some TextBoxes.
In VBA (If I have 5 TextBoxes named "TextBox1", "TextBox2", ... "TextBox5") I can use something like this:
For n = 1 To 5
Me("TextBox" & n).Text = NeededValue
Next n
I know that something like this is also possible in VB.Net but I wasn't able to find the right syntax (and I didn't find similar codes on SO).
I've tryed using
Me.Controls()
But I can't insert control name this way
Me.Controls.Find("TextBox" & n, True)
would be the similar approach to your VBA Style.
Use For Each and then test with TypeOf to find all TextBoxes in your form like :
For Each myObject1 As [Object] In Me.Controls
If TypeOf myObject1 Is TextBox Then
TryCast(myObject1, TextBox).Text = "NeededValue"
End If
Next
Also :
Dim myText = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5}
For Each btn In myText
btn.Text = "NeededValue"
Next
For i As Int32 = 1 To 5
Dim Txt = Me.Controls.Find("TextBox" & i, True)
If Txt.Length > 0 Then
Txt(0).Text = "blah"
End If
Next
Or :
For i As Int32 = 1 To 5
Dim Txt = Me.Controls.Find("TextBox" & i, True)
If Txt.Length > 0 Then
Txt(0).Text = "NeededValue"
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