Jinx Jinx - 6 months ago 46
Vb.net Question

disable and enable buttons vb.net

I want to disable the "OK" button when the validateAdd form loads, then enable the "OK" button when the user input some text in the textboxes.

Here is my code for disable and enable button.

Private Sub validateAdd_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If txtaddlname.Text = String.Empty AndAlso txtaddfname.Text = String.Empty AndAlso txtaddmid.Text = String.Empty Then
btnaddOk.Enabled = False
Else
btnaddOk.Enabled = True
End If
End Sub


Here is my validateAdd Form with empty textbox:
enter image description here

the button is already disabled but when i tried putting some text in it, the button is still disabled.
enter image description here

Answer

You should instead put all that code in the TextChanged event of the three textboxes:

Private Sub fields_TextChanged(sender As Object, e As EventArgs) Handles txtaddlname.TextChanged, txtaddfname.TextChanged, txtaddmid.TextChanged
    If txtaddlname.Text = String.Empty AndAlso txtaddfname.Text = String.Empty AndAlso txtaddmid.Text = String.Empty Then
        btnaddOk.Enabled = False
    Else
        btnaddOk.Enabled = True
    End If
End Sub

Since the Loaded event of a Form occurs only once. Hope it helps :)

Comments