Setting multi controls on a form

divjoy

Well-known member
Joined
Aug 25, 2013
Messages
159
Programming Experience
1-3
Hi,
I am setting all the textbox controls on a form to read only.

Then when the user clicks on a button I want to change all the textbox back to being editable!

Heres my code but it doesnt work or produce any errors. There are 7 textboxes on my form.

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'...Allow user to add and edit records...
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is TextBox Then
Dim txt As TextBox = CType(ctrl, TextBox)
txt.ReadOnly = False
MsgBox(txt.Name.ToString)
End If

Any help appreciated.
 
Hi,

I am not really sure what to say here since that code should work fine. Are you sure it is TextBox's that you should be checking for on your Form and not some other custom control / class that has been extended after inheriting the TextBox?

If it is TextBox's that you are trying to access then here is another option for you to try which does the same thing:-

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  For Each currentTextBox As TextBox In Me.Controls.OfType(Of TextBox)()
    currentTextBox.ReadOnly = False
  Next
End Sub


Hope that helps.

Cheers,

Ian
 
The first thing that comes to mind for me is that one or more of the TextBoxes are not on the form itself but some other container, e.g. a Panel or GroupBox. In that case they will be in the Controls collection of that container, not the form.
 
The first thing that comes to mind for me is that one or more of the TextBoxes are not on the form itself but some other container, e.g. a Panel or GroupBox. In that case they will be in the Controls collection of that container, not the form.

Ah Yes, that will be the most likely cause.:smile:

Cheers,

Ian
 
Yes you are correct the textbox controls are in Groupboxes so how would I handle that?

Regards

The first thing that comes to mind for me is that one or more of the TextBoxes are not on the form itself but some other container, e.g. a Panel or GroupBox. In that case they will be in the Controls collection of that container, not the form.
 
Without looping through control containers, you could set up your own array for those controls and loop though that:
        Dim boxes = {TextBox1, TextBox2, TextBox3}
        Array.ForEach(boxes, Sub(box) box.ReadOnly = Not box.ReadOnly)
 

Latest posts

Back
Top