How to put many Textbox in one If else statement - vb.net

This is the question
=If the FN button
will be click, then it will display a message base on the status of the textbox1 control. For the MN button, if
the event is click then it will display a message base on the status of the textbox2 control. The LN button
was clicked then it will display a message base on the status of the textbox3 control. Lastly, if the Clear
button control will be click and any of the textbox control is not empty then it will clear all the textbox
controls, but if all textbox controls are empty then it will show a message that all textbox controls are empty.
this is my code
Public Class Form1
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
Label1.Text = "First Name"
End Sub
Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label2.Click
Label2.Text = "Middle Name"
End Sub
Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
Label3.Text = "Last Name"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Text = "FN"
If TextBox1.Text = vbNullString Then
MessageBox.Show("The First name is empty")
Else MessageBox.Show("The First name is " & TextBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Button2.Text = "MN"
If TextBox2.Text = vbNullString Then
MessageBox.Show("The Middle name is empty")
Else : MessageBox.Show("The Middle name is " & TextBox2.Text)
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Button3.Text = "LN"
If TextBox3.Text = vbNullString Then
MessageBox.Show("The Last name is empty")
Else : MessageBox.Show("The Last name is " & TextBox3.Text)
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Button4.Text = "Clear"
If (TextBox1.Text) And (TextBox2.Text) = vbNullString Then
MessageBox.Show("Textbox control is empty")
Else : TextBox1.Clear()
End If
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
End Sub
End Class
My question is , how to work on clear button because i cant do it in Textbox2 and Textbox3 thankyou

Try something like this
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl
Try to add Next txt to your For Each

So, you are asking about Button4_Click.
This is what I was about to suggest first, because clearing all text boxes whether they are empty or not, is faster than first checking and then clearing.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
' Button4.Text = "Clear"
' If (TextBox1.Text) And (TextBox2.Text) = vbNullString Then
' MessageBox.Show("Textbox control is empty")
' Else : TextBox1.Clear()
' End If
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
MessageBox.Show("Textbox controls are empty")
End Sub
But then, if the intention is to a) just clear all textboxes, without any message if any one has some text. b) show the message only if all are empty.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
' Button4.Text = "Clear"
If (TextBox1.Text = vbNullString) And (TextBox2.Text = vbNullString) And (TextBox3.Text = vbNullString) Then
MessageBox.Show("Textbox controls are empty")
Else
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End If
or (if this works, VB6 is alien for me)
....
Else
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
End If
End Sub

I'd use a List(Of TextBox) allowing you to leverage All and ForEach:
Public Class Form1
Private TBs As New List(Of TextBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TBs.AddRange({TextBox1, TextBox2, TextBox3})
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If TBs.All(Function(tb) tb.Text = "") Then
MessageBox.Show("All TextBoxes are empty!")
Else
TBs.ForEach(Sub(tb) tb.Clear())
End If
End Sub
End Class

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
' Button4.Text = "Clear"
If (TextBox1.Text = vbNullString) And (TextBox2.Text = vbNullString) And (TextBox3.Text = vbNullString) Then
MessageBox.Show("Textbox controls are empty")
Else
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End If
thanks sir Tom Brunberg, this code works for me :)

Related

Visual Basics Watermark passwordchar?

I'm currently making a login form to my program where I have a watermark for the two textboxes Email and Password.
When a textbox is empty, its watermark text will appear in it like "Username" and "Password".
My code is:
Public Class frmLogin
Private Sub TextBox2_LostFocus(sender As Object, e As System.EventArgs)
If TextBox2.Text = "" Then
TextBox2.ForeColor = Color.DarkGray
TextBox2.Text = "Username"
End If
End Sub
Private Sub TextBox2_GotFocus(sender As Object, e As System.EventArgs) Handles TextBox2.GotFocus
TextBox2.Text = ""
TextBox2.ForeColor = Color.Black
End Sub
Private Sub TextBox1_GotFocus(sender As Object, e As System.EventArgs) Handles TextBox1.GotFocus
If TextBox2.Text = "" Then
TextBox2.ForeColor = Color.DarkGray
TextBox2.Text = "Username"
End If
TextBox1.Text = ""
TextBox1.ForeColor = Color.Black
End Sub
Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus
If TextBox1.Text = "" Then
TextBox1.ForeColor = Color.DarkGray
TextBox1.Text = "Password"
End If
End Sub
End Class
But now my problem is that I want to use password characters for the password. But I still want the watermark text to be in regular text. When I check to use a password char it turns my watermark into "**" instead of "Password". How can I fix that?
This seems good:
Private Sub TextBox1_GotFocus(sender As Object, e As System.EventArgs) Handles TextBox1.GotFocus
Textbox1.PasswordChar = "*"
Textbox1.Clear()
End Sub
Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus
TextBox1.PasswordChar = ControlChars.NullChar
End Sub

combobox multiple thread error

I have a problem with my code. I keep getting Multiple thread Error with backgroundworker, because of the combobox item display. Please look at my code below its a very simple code which I am planning to use on big scale, all I want it to do is "If item "1" selected show item "1" in label1. I can only assume that problem exists because Combobox runs in different thread....
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.runworkerasync()
BackgroundWorker1.WorkerReportsProgress = True
Me.Cursor = Cursors.WaitCursor 'Cursor changes to wait
End Sub
Public Structure controlwithtext
Public controlname As Control
Public text As String
Public Sub New(ByVal ctrl As Control, ByVal text As String)
Me.controlname = ctrl
Me.text = text
End Sub
End Structure
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If comboBox1.SelectedItem = "1" then
BackgroundWorker1.ReportProgress(5, New controlwithtext(Label1, ComboBox1.SelectedItem))
End If
End Sub
Private Sub SetBackgroundWorker_ProgressChanged(ByVal sender As Object,
ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If TypeOf e.UserState Is controlwithtext Then
Dim cwt As controlwithtext = CType(e.UserState, controlwithtext)
cwt.controlname.Text = cwt.text
End If
End Sub
Here's an example of how to read from and write to controls from the BackgroundWorker thread:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
While True
System.Threading.Thread.Sleep(250)
Dim selection As String = Me.Invoke(Function()
If Not IsNothing(ComboBox1.SelectedItem) Then
Return ComboBox1.SelectedItem.ToString
Else
Return String.Empty
End If
End Function).ToString
If selection = "1" Then
Me.Invoke(Sub()
Label1.Text = ComboBox1.SelectedItem.ToString
End Sub)
Else
Me.Invoke(Sub()
Label1.Text = "something else"
End Sub)
End If
End While
End Sub

automatic computaion

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
If String.IsNullOrEmpty(TextBox1.Text) OrElse String.IsNullOrEmpty(TextBox2.Text) Then Exit Sub
If Not IsNumeric(TextBox1.Text) OrElse Not IsNumeric(TextBox2.Text) Then Exit Sub
TextBox3.Text = CDbl(TextBox1.Text) + CDbl(TextBox2.Text)
End Sub
This code works for me but when i delete both value of the textbox the total is still there... any solution for my problem?
You have no code to remove the value from the output TextBox (TextBox3) when the input TextBoxes (TextBox1 and TextBox2) are cleared. You could just clear TextBox3 at the start of the TextChanged event handler.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
TextBox3.Text = ""
If String.IsNullOrEmpty(TextBox1.Text) OrElse String.IsNullOrEmpty(TextBox2.Text) Then Exit Sub
If Not IsNumeric(TextBox1.Text) OrElse Not IsNumeric(TextBox2.Text) Then Exit Sub
TextBox3.Text = (CDbl(TextBox1.Text) + CDbl(TextBox2.Text)).ToString
End Sub

Disable Button until multiple Textboxes got Validated

I have a form with over 10 textboxes and 1 button, I would like to disable the button with a realtime validation until all textboxes filled with a 10 or a 13 length numeric value, my code is the following so far:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
For Each userID As Control In Me.Controls.OfType(Of TextBox)()
AddHandler userID.TextChanged, AddressOf ValidateAllFields
Next userID
End Sub
Private Sub userID_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
Private Function ValidateAllFields()
Dim Validation As Boolean = True
For Each userID As Control In Me.Controls.OfType(Of TextBox)()
Dim e As New System.ComponentModel.CancelEventArgs
e.Cancel = False
Call userID_Validating(userID, e)
If e.Cancel = True Then Validation = False
Next userID
buttonSave.Enabled = Not Me.Controls.OfType(Of TextBox).Any(Function(userID) userID.Text.Length <> 10 AndAlso userID.Text.Length <> 13)
Return Validation
End Function
Private Sub userID_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles _
user00.Validating, _
user01.Validating, _
user02.Validating, _
user03.Validating, _
user04.Validating, _
user05.Validating, _
user06.Validating, _
user07.Validating, _
user07.Validating, _
user08.Validating, _
user09.Validating, _
user10.Validating, _
user11.Validating
If Not IsNumeric(sender.Text) OrElse (sender.Text.Length <> 10) AndAlso (sender.Text.Length <> 13) Then
ErrorProvider1.SetError(sender, "")
ErrorProvider2.SetError(sender, "Please enter a valid User ID.")
e.Cancel = True
Else
ErrorProvider1.SetError(sender, "Valid User ID.")
ErrorProvider2.SetError(sender, "")
End If
End Sub
Thanks to your help it works as I wanted, but can you help me improve/clean it? I'm still studying vb, I'm open to any suggestion. Thanks in advance!
Here you have a code performing the actions you want:
Dim done1, done2, done3 As Boolean
Dim targetLength1 As Integer = 10
Dim targetLength2 As Integer = 13
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
If (IsNumeric(TextBox1.Text)) Then
If (TextBox1.Text.Length = targetLength1 Or TextBox1.Text.Length = targetLength2) Then
done1 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Try
If (IsNumeric(TextBox2.Text)) Then
If (TextBox2.Text.Length = targetLength1 Or TextBox2.Text.Length = targetLength2) Then
done2 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
Try
If (IsNumeric(TextBox3.Text)) Then
If (TextBox3.Text.Length = targetLength1 Or TextBox3.Text.Length = targetLength2) Then
done3 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Enabled = False
End Sub
It accounts just for 3 textboxes (TextBox1, TextBox2 and TextBox3) and 1 button (Button1) but you can extend the idea to as many textboxes as you wish. It relies on the TextChanged even of each textbox. When the condition is met (given textbox has a number whose length is 10 or 13), the corresponding flag is set to true (e.g., done1 for TextBox1...). When all the flags are true (all the textboxes contain the expected information), the button is disabled.
I think would better to use TextChanged Event ..
Private Sub TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, ....., TextBox10.TextChanged
Chk4ButtonEnabled()
End Sub
Sub Chk4ButtonEnabled()
Dim s as String
For Each userID As Control In Me.Controls
If userID.GetType Is GetType(TextBox) Then
s = userID.Text
If Not s.Length = 10 OR Not s.Length = 13 Then
ErrorProvider1.SetError(userID, "")
buttonSave.Enabled = False
Else
ErrorProvider1.SetError(userID, "Valid User ID.")
buttonSave.Enabled = True
End If
End If
Next
End Sub

Get InvalidOperatorException was unhandled upon compiling

Everything was compiling just fine until validation for text fields was implemented.
Why won't it compile?
An error occurred creating the form.
See Exception.InnerException for
details. The error is: External
component has thrown an exception.
The source:
Public Class frmAddStudent
Dim aryData(6) As String
Public Shared newStudentRecord As String
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.DialogResult = DialogResult.Cancel
End Sub
Private Sub btnAddStudent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddStudent.Click
'place all the student field data into the array of elements
aryData(0) = txtFirstName.Text
aryData(1) = txtLastName.Text
aryData(2) = txtMajor.Text
aryData(3) = txtPhone.Text
aryData(4) = txtEmail.Text
aryData(5) = txtGPA.Text
'join the array elements and place the result into a string variable
newStudentRecord = Join(aryData, " ")
'create a link between the form and the file with streamwriter and write to the text file
If System.IO.File.Exists(frmMain.FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(frmMain.FILE_NAME, True)
objWriter.WriteLine(newStudentRecord)
objWriter.Close()
End If
Me.DialogResult = DialogResult.OK
End Sub
Private Sub txtFirstName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtFirstName.Validating
If txtFirstName.Text.Contains(" ") Or txtFirstName.Text.Length = 0 Or Not System.Text.RegularExpressions.Regex.IsMatch(txtFirstName.Text, "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtFirstName, "First Name can't contain spaces or be of zero length and must consist of only letters")
e.Cancel = True
Else
ErrorProvider1.SetError(txtFirstName, "")
End If
End Sub
Private Sub frmAddStudent_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ErrorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink
End Sub
Private Sub txtLastName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtLastName.Validating
If txtLastName.Text.Contains(" ") Or txtLastName.Text.Length = 0 Or Not System.Text.RegularExpressions.Regex.IsMatch(txtLastName.Text, "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtLastName, "Last Name can't contain spaces or be of zero length and must consist of only letters")
e.Cancel = True
Else
ErrorProvider1.SetError(txtLastName, "")
End If
End Sub
Private Sub txtMajor_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtMajor.Validating
If txtMajor.Text.Length > 0 Then
If Not System.Text.RegularExpressions.Regex.IsMatch(Strings.Left(txtMajor.Text, 1), "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtMajor, "Major course code is incorrect")
Else
ErrorProvider1.SetError(txtMajor, "")
End If
Else
ErrorProvider1.SetError(txtMajor, "Major cant' be zero length")
End If
End Sub
End Class
EDIT: Here's also a link to a PrtSc of the problem: http://img88.imageshack.us/i/imageqc.gif/