Visual Basic minimum 5 characters validation - vb.net

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

Related

Is there something wrong with my coding? I am still new

I try to run this program but an error always appears:
Conversion from the string "LBLBuku" to type' Double 'is not valid.
If LBLBuku.Text >= 5 Or Val(LBLBuku.Text) + Val(TextBox1.Text) > 5 Then
MsgBox("Peminjaman Melebihi")
Else
If lbljudul.Text = "" Or TextBox1.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
lbljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
Call rumustotalbuku()
End If
End If
Notice on your code the line
LBLBuku.Text >= 5
The property Text is of type String, you would have to convert the text to an integer type first before you can use ">=".
First I declare a variable to hold the integer value in the Text Box. Integer.TryParse will return true if it can convert the string in the text box to an integer. It will also fill the variable intTB1 with the number.
I am assuming that LBLBuku is a label so the .Text property has been set from code. We can depend on this being a number so all we need to do is the conversion with CInt(). We can use the variable we got from the .TryParse in the Or CInt(LBLBuku.Text) + intTB1 > 5 instead of referring to the text box again.
We don't need to check if TextBox1 is empty because it wouldn't have passed the .TryParse if it was.
Last and probably least, you don't need the Call keyword in most situations.
You do realize that you have added TextBox2 twice to the new DataRow.
Private Sub OPCode()
Dim intTB1 As Integer
If Not Integer.TryParse(TextBox1.Text, intTB1) Then
MessageBox.Show("Please enter a number in TextBox1.")
Return
End If
If CInt(LBLBuku.Text) >= 5 Or CInt(LBLBuku.Text) + intTB1 > 5 Then
MsgBox("Peminjaman Melebihi Maksimal")
Else
If lbljudul.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
bljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
rumustotalbuku()
End If
End If
End Sub

VBA Input Box will not close

I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.
Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?
Here is the code in written form:
Sub Pword()
Dim Ans As Boolean
Const Pword As String = "black2"
Ans = False
Do While Ans = False
If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
Ans = True
End If
Loop
Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""
MsgBox "All data has been cleared."
End Sub
If you need to consider an empty string as a valid input value, the only way to check if the InputBox was actually cancelled isn't to compare its result with vbNullString or "" (both will be True).
So you can use the (undocumented) StrPtr function to determine if the InputBox call returned a legit empty string, or if it was actively cancelled with the [X] or [Cancel] button:
Dim result As String
result = InputBox(...)
If StrPtr(result) = 0 Then
' inputbox was cancelled
Exit Sub
Else
' todo: validate result
End If
Combine that with the other answers to get a reliable "retry" mechanism.
Add a check to see if it's an empty string, like this:
Dim sResult As String
Do While Ans = False
sResult = InputBox("Please enter password to continue.", "Enter Password")
If sResult = Pword Then
Ans = True
ElseIf sResult = "" Then
Exit Do ' or Exit Sub depending on what you want to happen afterwards
End If
Loop
#braX suggestion is an excellent solution.
Also, you can limit the attemps to n in this case I limit the attempts to 3
Dim sResult As String
Dim Attmp As Integer
Attmp = 0
Do While Ans = False
sResult = InputBox("Please enter password to continue.", "Enter Password")
If sResult = Pword Then
Ans = True
ElseIf sResult = "" Then
Attmp = Attmp + 1
If Attmp = 3 Then
Msgbox "Maximum attempts reached."
Exit Do
End If
End If
Loop

Focus on a TextBox based on its input check

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()

Option Strict On, set Focus of unknown object type

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.

How to Supply Default Value in DataGridView

I need to find a way to supply a default value if the user leaves a cell blank in my datagridview. Right now I'm able to display an error message if the user leaves the cell blank but I also want to insert a default text in the cell after the message pops up. For example if the cell requires a name and the user leaves it blank, a message will pop up and tell the user that he/she cannot leave the name blank. After this I want the text "name" to populate the cell
If (e.ColumnIndex = 0) Then 'checking numeric value for column 1 only
Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
if cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
MessageBox.Show("Please Enter a Value")
Exit Sub
End If
Try:
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "default value"
Pass a default value into DatagridView empty cell:
For k As Integer = 0 To DataGridView1.Rows.Count - 1
For l = 0 To DataGridView1.ColumnCount - 1
Dim cellData = DataGridView1.Rows(k).Cells(l).Value
If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
DataGridView1.Rows(k).Cells(l).Value = "0"
End If
Next
Next