kodkod kodkod - 5 months ago 19
Vb.net Question

disable a button based on three textbox fields

I'm quite new to VB.net (and VS 2008), so I'm afraid my question might be basic, but I'm not sure how to solve it.

I have a winform with three textbox fields and a button. All textbox fields must be filled before the user can click the button to continue. To this end I would like to disable the button as long as there is at least one empty textbox.

If I had only one textbox field, it would be easy for me to do. In the

Textbox1_Leave
event I would check if
Textbox1.Text
is not empty and if so, set
Button1.Enabled = True
.

But what should I do if I have three textboxes? Have three event handlers, one for each textbox? Or is there a way I'm not familiar with?

Many thanks.

Answer
AddHandler Textbox1.TextChanged, AddressOf ValidateInputs
AddHandler Textbox2.TextChanged, AddressOf ValidateInputs
AddHandler Textbox3.TextChanged, AddressOf ValidateInputs

Private Sub ValidateInputs(ByVal Sender As Object, ByVal e as EventArgs)
    Button1.Enabled = Not (Textbox1.Text = String.Empty OrElse Textbox2.Text = String.Empty OrElse Textbox3.Text = String.Empty)
End Sub

And, even better, if these controls all have the same parent, and are the only textboxes in the parent (say, all nested in a groupbox), you can do it something like this:

For Each t As TextBox In GroupBox1.Controls.OfType(Of Textbox)
   AddHandler t.TextChanged, AddressOf ValidateInputs
Next t

Private Sub ValidateInputs(ByVal Sender As Object, ByVal e as EventArgs)
    Button1.Enabled = Not GropuBox1.Controls.OfType(Of Textbox).Any(Function(t) t.Text = String.Empty)
End Sub