I want my program to check whether the inputs in a TextBox meet certain condition. If the target condition is not met, the cursor should focus back on that particular TextBox.
My code:
Private Sub ButtonSubmit_Click(sender As Object, e As EventArgs) Handles ButtonSubmit.Click
EnterVotes.LabelCan1.Text = CandName1.Text
EnterVotes.Labelcan2.Text = CandName2.Text
EnterVotes.LabelCan3.Text = CandName3.Text
EnterVotes.LabelCan4.Text = CandName4.Text
EnterVotes.LabelCan5.Text = CandName5.Text
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
End If
loading.Show()
Me.Hide()
If CandName1.Text = "" Then //Show your message here // CandName1.focus()//to return to that textbox Else //Show your
message here End If
use the method focus() to return and re-write into that textbox
It is actually quite simple
just check if the value of the text is > 1
then put focus on the textbox
heres an example
if txtbox.text.value < 1 then
messagebox.show("You must enter data for textbox")
txtbox.focus()
end if
and then continue method for each text box you are working with
Could get fancy and use some linq to go threw your names.
Dim Candidate() As TextBox
Candidate = Me.Controls.OfType(Of TextBox)().Where(Function(c) c.Name.Contains("CandName")).ToArray()
Dim i As Integer = 0
While i < Candidate.Count
If(Candidate(i).text.value < 1)
MessageBox.Show("Please enter a name in Candidate " & (i + 1).ToString())
Candidate(i).Focus()
Exit While
End If
i += 1
End While
This way you can check all your candidates in one shot. This is untested code, but I think it should work.
You can play around with this and edit however you please it's pretty flexible at this point.
I think this might be the way but not very efficient.
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Else
CandName2.Focus()
End If
If CandName2.Text = "" Then
MessageBox.Show("Please enter an name in Candidate 2")
CandName3.Focus()
Else
CandName3.Focus()
End If
If CandName3.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 3")
CandName3.Focus()
Else
CandName4.Focus()
End If
If CandName4.Text = "" Then
MessageBox.Show("Please enter a name in candidate 4")
CandName4.Focus()
Else
CandName5.Focus()
End If
If CandName5.Text = "" Then
MessageBox.Show("Pleae enter a name in candidat 5")
CandName5.Focus()
Else
loading.Show()
End If
If String.IsNullOrWhitespace( CandName1.Text ) Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Return
End If
... for all five
loading.Show()
Me.Hide()
You want to make sure to exit this early with the Return statements so you don't get to the code:
loading.Show()
Me.Hide()
Related
I have a program where the user enters a quantity in a field and the price is automatically calculated. I want to only allow numbers in this field and can't figure out a way to do so.
All I Currently have is a small pop up message that occurs when a user enters a number over 1000. But it still lets them go through with it if they just click okay.
Private Sub txt2x6LumberQuantity_TextChanged(sender As Object, e As EventArgs) Handles txt2x6LumberQuantity.TextChanged
'Text changed event that occurs when the text within the textbox is changed'
'If statement to check if the number is between 0 and 1000, if is it'll go to the next block of code and if not goes to the else'
If IsNumeric(txt2x6LumberQuantity.Text) = True Then
Select Case CInt(txt2x6LumberQuantity.Text)
Case 0 To 1000
'Calculates line total with a function'
dec2x6LumberLineTotal = calculate2x6LumberLineTotal(CDec(lbl2x6LumberPrice.Text), CDec(txt2x6LumberQuantity.Text), lbl2x6LumberLineTotal)
'Calculates the subtotal'
calculateSubtotal(dec2x6LumberLineTotal, dec2x4LumberLineTotal, decOneHalfPlywoodLineTotal, decFiveEighthsPlywoodLineTotal, decNailsLineTotal, decBradsLineTotal, decGalvanizedScrewLineTotal, decSledgeHammerLineTotal, decFiveDrillBitsLineTotal, decStapleGunLineTotal)
'Calculates the tax'
calculateTax(decSubtotal)
Case Else
MsgBox("Choose a quantity between 0 and 1000", MsgBoxStyle.Information, "Quantity entered is invlaid.")
txt2x6LumberQuantity.Focus()
End Select
End If
End Sub
Example:
USING THE VALIDATE EVENT PROCEDURE
Private Sub txtAge_Validate(Cancel As Boolean)
If Not IsNumeric(txtAge.Text) Then
Cancel = True
ElseIf txtAge.Text < 21 Then
Beep 'give the user some minimal feedback
MsgBox "Enter an age greater than 21"
Cancel = True
'Following is not needed. Placed here for clarity
Else
Cancel = False
End If
End Sub
I am updating some code to allow for Option Strict On. One issue that is coming up, is late binding. I have a Form with multiple required items of different types (TextBox, ComboBox, etc.).. I have a function to check the validity of the Form, and then set the focus to the first control that doesn't have a value.
Without Option Strict On, I could simply have a basic Object, and set that to whichever control was missing a value, and then call objMissing.Focus() at the end, but with Option Strict On, the compiler doesn't allow the late binding.
I realize that if the controls were all the same type, I could cast the missing object to a TextBox, for example. Is there a way I can still do this using one variable to store the control to set focus to? Or should I just set the Focus immediately in each of the Ifs that are checking for a value?
Here is an example of the code I am looking at (txt_ are TextBox, cbo_ are ComboBox, btn_ are Button types):
Dim objMissing as Object
If txtItemDescription.Text = String.Empty Then
objMissing = txtItemDescription
strMessage = "You must enter an item description."
ElseIf cboProductType.Text = String.Empty Then
objMissing = cboProductType
strMessage = "You must select a product type."
ElseIf cboComponentType.Text = String.Empty And cboComponentType.Enabled Then
objMissing = cboComponentType
strMessage = "You must select a component type."
ElseIf txtOnHand.Text = String.Empty Then
txtOnHand.Text = "0"
ElseIf txtRented.Text = String.Empty Then
txtRented.Text = "0"
ElseIf txtCost.Text = String.Empty Then
txtCost.Text = "0.00"
ElseIf txtFreight.Text = String.Empty Then
txtFreight.Text = "0.00"
ElseIf Len(txtBarcodePrefix.Text) < 6 Then
objMissing = txtBarcodePrefix
strMessage = "You must enter a 6-digit barcode prefix."
ElseIf cboCondition.Text = String.Empty Then
objMissing = cboCondition
strMessage = "You must enter a condition."
ElseIf btnComponents.Enabled And Me.ComponentList.Count = 0 Then
objMissing = btnComponents
strMessage = "You must select the item components."
ElseIf txtSerialNumber.Text <> String.Empty AndAlso txtOnHand.Text <> String.Empty Then
If CInt(txtOnHand.Text) > 1 Then
objMissing = txtOnHand
strMessage = "You cannot have more than 1 item on hand with the same serial number."
End If
End If
If objMissing IsNot Nothing Then
MessageBox.Show(strMessage)
objMissing.Focus()
End If
If you declare objMissing as type Control, then your code will work as you want. All standard WinForms controls should inherit from Control.
So I've been working on this project for a couple of weeks, as I self teach. I've hit a wall, and the community here has been so helpful I come again with a problem.
Basically, I have an input box where a user inputs a name. The name is then displayed in a listbox. The name is also put into an XML table if it is not there already.
There is a button near the list box that allows the user to remove names from the list box. This amends the XML, not removing the name from the table, but adding an end time to that name's child EndTime.
If the user then adds the same name to the input box, the XML gets appended to add another StartTime rather than create a new element.
All of this functions well enough (My code is probably clunky, but it's been working so far.) The problem comes when I try to validate the text box before passing everything through to XML. What I am trying to accomplish is that if the name exists in the listbox on the form (i.e hasn't been deleted by the user) then nothing happens to the XML, the input box is cleared. This is to prevent false timestamps due to a user accidentally typing the same name twice.
Anyhow, I hope that makes sense, I'm tired as hell. The code I've got is as follows:
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles addPlayerButton.Click
playerTypeCheck()
addPlayerXML()
clearAddBox()
End Sub
Private Sub playerTypeCheck()
If playerTypeCBox.SelectedIndex = 0 Then
addMiner()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
addHauler()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
addForeman()
End If
End Sub
Private Sub addMiner()
If minerAddBox.Text = String.Empty Then
Return
End If
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : minerListBox.Items.Add(UCase(minerAddBox.Text))
End If
If ComboBox1.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : ComboBox1.Items.Add(UCase(minerAddBox.Text))
End If
End Sub
Private Sub addPlayerXML()
If System.IO.File.Exists("Miners.xml") Then
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim nod As XmlNode = xmlSearch.DocumentElement()
If minerAddBox.Text = "" Then
Return
Else
If playerTypeCBox.SelectedIndex = 0 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 1 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Haulers/Hauler[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 2 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Foremen/Foreman[#Name='" + UCase(minerAddBox.Text) + "']")
End If
If nod IsNot Nothing Then
nodeValidatedXML()
Else
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newPlayer As String = ""
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners")
If playerTypeCBox.SelectedIndex = 0 Then
newMinerXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
newHaulerXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
newForemanXML()
End If
End If
End If
Else
newXML()
End If
End Sub
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
minerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
haulerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
foremanValidatedXML()
End If
End Sub
Private Sub minerValidatedXML()
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = False Then
appendMinerTimeXML()
End If
End Sub
Private Sub appendMinerTimeXML()
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newStartTime As String = Now & ", "
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" & UCase(minerAddBox.Text) & "']/StartTime")
docFrag.InnerXml = newStartTime
nod2.AppendChild(docFrag)
xmlSearch.Save("Miners.xml")
End Sub
And lastly, the clearAddBox() subroutine
Private Sub clearAddBox()
minerAddBox.Text = ""
End Sub
So, I should point out, that if I rewrite the nodeValidated() Subroutine to something like:
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
appendMinerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
appendHaulerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
appendForemanTimeXML()
End If
End Sub
then all of the XML works, except it adds timestamps on names that already exist in the list, which is what i'm trying to avoid. So if I haven't completely pissed you off yet, what is it about the minerValidated() subroutine that is failing to call appendMinerTimeXML()? I feel the problem is either in the minerValidated() sub, or perhaps clearAddBox() is somehow firing and I'm missing it? Thanks for taking the time to slog through this.
Edit: Clarification. The code as I have it right now is failing to append the XML at all. Everything writes fine the first time, but when I remove a name from the list and then re-add, no timestamp is added to the XML.
You need to prevent the user accidentally typing the name twice.(Not sure if you mean adding it twice)
For this I believe you need to clear the minerAddBox.Text in your addminer() if this line is true.
minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True
minerAddBox.Text = ""
Return
Now it will return back to your addplayerXML which will Return to your clearbox(), since you have this in your addplayerXML()
If minerAddBox.Text = "" Then
Return
Now you get to your clearbox() (Which is not really needed now since you cleared the minerAddBox.Text already)
when I remove a name from the list and then re-add, no timestamp is added to the XML.
your minerValidatedXML() is true, because you are not clearing the textbox when you re-add a name to the list box. Or you may need to remove the existing listbox item if it is the same as the textbox
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
minerListBox.Items.remove(UCase(minerAddBox.Text))
I was actually working an Attendance System, using listbox i want to monitor whether "employees" timed in or out.
txtEmpNum.text as my textbox,
rdTin as my radio button for time in,
rdTout as my radio button for time out,
lblName, lblDept, lblinout are just label. I want that if a user already timed in his/her name wont appear on my listbox rather msgbox pop up. But on this code although msgbox poped up, still the name of the employee appears on my listbox.
If txtEmpNum.Text = 8888 Then
If rdTin.Checked = True Then
For i As Integer = 0 To listEmp.Items.Count - 1
If (listEmp.Items(i).ToString.Contains("Bane Lim")) Then
MsgBox("String found at " & (i + 1).ToString)
Exit For
End If
Next
lblName.Text = "Bane"
lblDept.Text = "Admin"
lblinout.Text = "In"
listEmp.Items.Add("Bane Lim")
txtEmpNum.Clear()
ElseIf rdTout.Checked = True Then
lblName.Text = "Bane"
lblDept.Text = "Admin"
lblinout.Text = "Out"
listEmp.Items.Remove("Bane Lim")
txtEmpNum.Clear()
End If
Is the problem that the name is appearing a second time? You'll want to Exit Sub or Exit Function rather than Exit For. Exit For is kicking it from the loop but continuing with the remaining code (to add again).
Otherwise add a flag in there like:
If txtEmpNum.Text = 8888 Then
If rdTin.Checked = True Then
Dim bolFound As Boolean = False
For i As Integer = 0 To listEmp.Items.Count - 1
If (listEmp.Items(i).ToString.Contains("Bane Lim")) Then
MsgBox("String found at " & (i + 1).ToString)
bolFound = True
Exit For
End If
Next
If Not bolFound Then
lblName.Text = "Bane"
lblDept.Text = "Admin"
lblinout.Text = "In"
listEmp.Items.Add("Bane Lim")
txtEmpNum.Clear()
End If
ElseIf rdTout.Checked = True Then
lblName.Text = "Bane"
lblDept.Text = "Admin"
lblinout.Text = "Out"
listEmp.Items.Remove("Bane Lim")
txtEmpNum.Clear()
End If
How would I go about making sure that when a user inputs his "Combination" into the input box, it has to be at least 5 characters?
This is what code I have so far:
If (tboxStatus.Text) = "Combination Not Set" Or (tboxStatus.Text) = "UnLocked" Then
Combination = CInt(InputBox("Set the Combination First"))
tboxStatus.Text = "Locked"
ElseIf (tboxStatus.Text) = "Locked" Then
MsgBox("You must first UnLock the safe before trying to change the combination.")
End If
For starters...
Dim value as String = InputBox("Set the Combination First")
If (value.Trim.Length < 5) Then
MsgBox ("Combination must be at least 5 characters")
Else
Combination = CInt(value)
End If
Among other things, you'll need to check if it's numeric before doing a CInt()
If tboxStatus.Text = "Combination Not Set" OrElse tboxStatus.Text = "UnLocked" Then
Dim result As String = ""
While String.IsNullOrWhiteSpace(result) OrElse Not Integer.TryParse(result, Combination)
result= InputBox("Set a Combination Number First")
End While
tboxStatus.Text = "Locked"
ElseIf tboxStatus.Text = "Locked" Then
MsgBox("You must first UnLock the safe before trying to change the combination.")
End If