Select Textbox using For Loop - vb.net

Sorry this is weird and silly question but I need a solution of this...
I have 30 textboxes named as Txt1,Txt2,Txt3,...,Txt30
I have to fill textbox as Txt1.text = 0 on button click..
Is there any way like On Button Click
Dim i as Integer
For i = 1 to 30 '----- Possible in string but don't know if possible in textboxes
Txt(i).text = 0
Next
Or I have to write all 30 lines like
Txt1.text = 0
...
Txt30.text = 0
I don't know how this question asked, maybe Question improper.
Thanx in Advance...

If the textboxes are all contained in Controls collection of the Form, then it is really easy to loop over them
For Each(t in Me.Controls.OfType(Of TextBox)())
t.Text = "0"
Of course the advantage of this approach is that you don't have to worry if you add other textboxes to your form. They will be found using the foreach loop without having a fixed top limit.
And, if not all of your textboxes should be included in the loop, then you can simply use the Tag property of the textboxes that you want to use. For example, if you set the Tag property to the string "Y", then you can change the foreach loop to find only the controls with the matching Tag property
For Each t in Me.Controls.OfType(Of TextBox)() _
.Where(Function(x) x.Tag = "Y")
t.Text = "0"
The two solutions above works well if all your textboxes are contained in the same container (Form, GroupBox or Panel), instead, if these textboxes are dispersed in different containers (some in a groupbox, others in a panel etc) then you can build a List(Of TextBox) variable filling it with the textboxes instances and use it when the need arise
Dim myTexts = New List(Of TextBox)() From { Txt1, Txt2, Txt3, ....}
And loop over this variable

You can do as Steve said, but if you have other textboxes that you don't want to edit then there is another way:
For i = 1 to 30
dim found = Me.Controls.Find("Txt" & i, True) '<- the True argument is for recursive search
If Not IsNothing(found) AndAlso found.Length > 0 Then
found(0).Text = "0"
End If
Next
If your textboxes are all in the same control, for example GroupBox, you can do GroupBox.Controls.Find saving CPU resources

Related

How do I fill the first empty TextBox in a GroupBox?

I have a GroupBox with multiple TextBox controls and I can check to see if any are empty just fine but I'm trying to make my program fill the first empty textbox it finds in the GroupBox.
Code:
Dim empty = From txt In grpbill.Controls.OfType(Of TextBox)()
Where txt.Text.Length = 0
If empty.Any Then
End If
Any ideas?
You're almost there. I'm unsure on how you define first but I've gone off the TabIndex property:
Dim firstEmptyTextBox As TextBox = (From txt In GroupBox1.Controls.OfType(Of TextBox)()
Where txt.Text.Length = 0
Order By txt.TabIndex Ascending).FirstOrDefault()
If firstEmptyTextBox IsNot Nothing Then
firstEmptyTextBox.Text = "Text"
End If
You can use the .FirstOrDefault() method:
Returns the first element of a sequence, or a default value if the sequence contains no elements.
In my example I have three TextBox controls. The first one has the text Not empty whilst the other two have nothing. When I run the code, this is my output:
Here another idea which will also work in cases where all TextBox controls in GroupBox are not empty.
Private Sub SetTextJForFirstEmptyTextBoxIfExists(text As String)
Dim emptyTextBoxes As IEnumerable(Of TextBox)
= grpbill.Controls.
OfType(Of TextBox)().
Where(Function(txtbox) txtbox.Text.Length = 0)
For Each emptyTextBox In emptyTextBoxes
emptyTextBox.Text = text
Exit Sub
Next
End Sub

Verify multiple comboboxes/textboxes have value

I have a winform that has about 6 comboboxes and 3 textboxes. I also have a button that takes the values of aforementioned controls and inserts them into SQL. Is there a better way, than a bunch of nested if/then statements, to verify that the controls all have values before inserting the data? This gets ugly very fast. I have tried googling this answer, but I get too many ASPx answers. I will entertain any ideas you may have. I am just trying to find a better way to do this. Thanks for any help.
I think its not too hard.
This code shows error message about the first empty textbox or combobox. But you can easily modify to show error message for all empty comboboxes and textboxes if required.
Private Function ValidateMyControls() As Boolean
Dim allComboBoxes() As ComboBox = {ComboBox1, ComboBox2, ComboBox3} ' add all your comboboxes here
Dim allTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3} ' add all your textboxes here
Dim emptyTB As TextBox = allTextBoxes.Where(Function(f) f.Text = "").FirstOrDefault
Dim emptyCB As ComboBox = allComboBoxes.Where(Function(f) f.SelectedIndex = -1).FirstOrDefault
If emptyTB IsNot Nothing Then
MessageBox.Show("Please fill value in " & emptyTB.Name)
Return False
ElseIf emptyCB IsNot Nothing Then
MessageBox.Show("Please select a value in dropdown " & emptyCB.Name)
Return False
Else
' All set to go!
Return True
End If
End Function

Visual Basic 2008 - Me.Controls - Textboxes - NULL -

Self taught(in progress) Visual Basic guy here.
I've searched for a clear answer on this, but so far have come up empty handed.
The problem...
I have two comboboxes. The first combobox has 10 options, second combobox has 2 options
I have 10 textboxes, with a name that includes one of the 10 options.
ex 1st textbox name - "txb_Option1Type"
2nd textbox name - "txb_Option2Type" and so on.
I have 2 tabs, with the first 5 text boxes on the 1st tab and last 5 on the 2nd tab.
I thought the following bit of code, upon a button click, would transfer the text of the chosen option in the 2nd combobox to the corresponding textbox...
`
Public Sub TransferTruckToDoorText()
Dim str_ErrorButton As String = cbx_DoorNumber.Text
Dim str_ReplaceSpacesButton As String = str_ErrorButton.Replace(" ", "")
Dim str_Button As String = str_ReplaceSpacesButton
' Null reference error on below line of code
Me.Controls("txb_" & str_Button & "Type").Text = cbx_TruckType.Text
End Sub
`
As noted in the above code, I'm getting a null reference and for the life of me cannot figure out why. I've stepped through the code, and I'm not able to find a NULL or Nothing value that could be making this catch.
Any and all help would be appreciated.
edited for clarity
The Me.Controls collection does not automatically search the child panels.
Try using the Controls.Find method for that, which includes a parameter to search the child control's control collection, too. It returns an array:
Dim c As Control() = Me.Controls.Find("txb_" & str_Button & "Type", True)
If c.Length = 1 Then
c(0).Text = cbx_TruckType.Text
End If
Me.Controls.Item("txb_" & str_Button & "Type")

String to Object as Expression

I have multiple TextBox controls Monday that will hold a value. I want to be able to add up all of the Monday textboxes and store that value as monTotal. I am getting an error message that says string cannot be converted to integer.
For i As Integer = 1 To rowCount Step 1
Dim var As Object
var = "txtMonday" & i & ".Text"
monTotal = monTotal + CInt(var)
Next
The way you are attempting to obtain a reference to the text boxes is not idiomatic of VisualBasic .NET.
var = "txtMonday" & i & ".Text" ' this is not a way to obtain a reference to the text box's text
While it would be possible to accomplish something like that using reflection, you'd be much better off refactoring your code to use an array of text boxes.
Since you are probably using Windows Forms you could perhaps implement logic to find the text box control you are interested in on the form using something like this:
' assuming container is the control that contains the text boxes
For Each ctrl In container.Controls
If (ctrl.GetType() Is GetType(TextBox)) Then
If ctrl.Name.StartsWith("txtMonday") Then
Dim txt As TextBox = CType(ctrl, TextBox)
monTotal = monTotal + CInt(txt.Text)
End If
End If
Next
The example above assumes that all the txtMonday.. text boxes are placed inside a control named container. That could be the form itself, or some other panel or table.
If all the textboxes live on the form and there are none being used for other text work you could use this. You could place all the textboxes that contain values your looking for in a separate container and get them like below, but use that control collection.
Dim amount As Double = 0
For Each tb As Textbox In Me.Controls.OfType(Of Textbox)()
amount += Convert.ToDouble(tb.Text)
Next
Dim monTotal as double=0
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is TextBox AndAlso ctrl.Name.StartsWith("txtMonday") Then
monTotal = monTotal + val(ctrl.Text)
End If
Next

Looping through Controls in VB.NET

I am creating a chess program. And it is composed of sixty four picture boxes with alternating black and white background colours.
I have named them pba1, pba2, pbb1, pbb2, pbc1 and so on.
Now, I want to loop through only the black ones, for example, I want to loop through only, pba1, pbb2, pbc3 and so on.
How do I create a loop for this in VB.NET?
I know of the way to loop through similarly named controls, but I am not able to adapt that method for my problem. Can you tell me a solution?
EDIT: In pba1, pb stands for picture box, and a1 stands for the square. Just in case, you wonder why such a name.
EDIT: Check out this answer
Loop through the PictureBox's in your ControlCollection and test for BackColor. I used the Form's ControlCollection, if they are in some other type of container control use that.
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is PictureBox Then
If cntrl.BackColor = Color.Black Then
'Do Something
End If
End If
Next
Base on the additional information that you gave in your answer, the reason your example is not working is that the Controls Name is a String and you are comparing it to the PictureBox Control not the Name of the Control.
You can try using the Tag Property instead of the Name of the Control, it will be cleaner and easier to read. I just put a 1 in the PictureBox's Tag Property for Black and a 0 for White.
Private Sub OriginalColour()
For Each cntrl As Control In Me.Controls
Dim result As Integer
If TypeOf cntrl Is PictureBox Then
If Integer.TryParse(cntrl.Tag.ToString, result) Then
If result = 1 Then
cntrl.BackColor = Color.Gray
Else
cntrl.BackColor = Color.White
End If
End If
End If
Next
End Sub
Generating controls at design time via the Forms Designer only makes sense for layouts which benefit from the forms designer.
In your case, you just have 64 uniform boxes in 8 rows of 8. Don’t use the Forms Designer for this, create the controls at runtime, and don’t give them names like pba1, just put them into an appropriate data structure (such as an 8x8 array):
Private chessFields As PictureBox(8, 8)
' In Form_Load:
For i = 0 To 7
For j = 0 To 7
chessFields(i, j) = New PictureBox
' Set size, position … then, finally,
Controls.Add(chessFields(i, j))
Next
Next
That way, you can access the fields in an orderly fashion without having to go via the Form.Controls collection.
Put all the pictureboxes in an 8x8 tableLayoutPanel (also useful for scaling etc). Then
For Each pb As PictureBox In TableLayoutPanel1.Controls
Dim col As Integer = TableLayoutPanel1.GetCellPosition(pb).Column
Dim row As Integer = TableLayoutPanel1.GetCellPosition(pb).Row
If col Mod 2 = 0 Xor row Mod 2 = 0 Then
pb.BackColor = Color.Black
Else
pb.BackColor = Color.White
End If
Next
Of course you could also use an array of the squares if you have that available.
This will not affect the events (pba1.click etc).
This is fairly simple and it may be resource heavy, but it works. I have a form with 36 CheckBoxes. This takes advantage of the fact that when you copy a checkbox it just increases the number of the name. I ended up with 36 checkboxes named CheckBox1 thru Checkbox36. The Function returns a checkbox, which may be used to set or read any property.
Private Function GetCheckBox(ByVal Index As Integer) As CheckBox
Dim CKBox As checkbox
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
CKBox = cntrl
If CKBox.Name = "CheckBox" & Index Then
Exit For
End If
End If
Next
Return ckbox
End Function