.NET Main Menu Help - vb.net

I'm trying to make a main menu which accepts user input and then checks inputted password for validity against passwords I hardcoded into an array.
Firstly, in the for loop, only the first password index is being checked. I'd like the inputted password to be checked against EACH password inside the ValidPasswords() array.
Second, My for loop isn't doing what I want it to do. I'd like to give the user 3 chances to enter a password... If he/she exceeds 3, it tells them they've tried 3 times and exits the form. Right now, it just loops 3 times and exits without giving the user a chance to try again. If I put a return statement in, it just keeps returning and doesn't loop 3 times.
Public Class frmMain
Dim ValidPasswords() = {"1234", "2222", "8918", "9911"}
'Dim ValidPWList As New List(Of String)
Dim pwIndex As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' For pwIndex = 0 To ValidPasswords.Length 'TOTAL PASSWORDS
If txtPW.Text = ValidPasswords(pwIndex) Then
Else
For i = 0 To 2 '3 MAX ALLOWABLE ATTEMPT
MessageBox.Show("Invalid Password, Please try again.", "Invalid Credentials")
txtPW.Focus()
Next
MessageBox.Show("Exceeded 3 password attempts.")
Me.Close()
End If
If txtFNAME.Text = "" Then
MessageBox.Show("Please enter your name!", "Error")
'ElseIf txtPW.Text <> "1234" And txtPW.Text <> "2332" And txtPW.Text <> "0192" And txtPW.Text <> "2010" Then
'MessageBox.Show("Invalid Password, Please try again.", "Invalid Credentials")
Else
g_welcomeMessage = ("Welcome, " + txtFNAME.Text + " " + txtLNAME.Text + ", to Image Viewer 1.0")
frmImage.ShowDialog()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MessageBox.Show("Thanks for trying me out!", "Goodbye")
Me.Close()
End Sub
Thanks!

You got things back to front there Daniel. I'll not bore you with advice on hardcoded passwords in your application and assume you're just trying to grasp the basics... I'll also assume .Net 4 because you haven't specified ;-)
I'm doing this by hand so excuse any minor syntax issues:
Public Class frmMain
Private validPasswords As List(Of String) = New List(Of String) From {"1234", "2222", "8918", "9911"}
Private failedAttempts As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If String.IsNullOrWhitespace(txtFNAME.Text) Then
MsgBox("Please enter a name")
Return
End If
If ValidPasswords.Any(Function(x) String.Equals(txtPW.Text, x)) Then
' User has a name and entered a valid password...
g_welcomeMessage = ("Welcome, " + txtFNAME.Text + " " + txtLNAME.Text + ", to Image Viewer 1.0")
frmImage.ShowDialog()
Else
failedAttempts += 1
If failedAttempts = 3 Then
MessageBox.Show("Exceeded 3 password attempts.")
Me.Close()
End If
End If
End Sub
' The other method here...
End Class

Related

Creating a login/register form

I'm working on a vb form, which allows a person to create an "account". I store the usernames and passwords in two arrays, and extract the information from them. But when I run the program, it comes up with a problem:
"An unhandled exception of type 'System.ArgumentNullException'
occurred in Microsoft.VisualBasic.dll, Additional information: Value
cannot be null."
where the code for the Button2/Register Button is (To be exact:
For i = 0 To (UBound(Usernames))
Could you help me out and tell me what to do differently/how to approach this situation? Here is the code:
Public Class Form1
Dim Usernames() As String
Dim Passwords() As String
Dim CurrName As String
Dim i As Integer
'Login button is pressed
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Index As Integer
CurrName = TextBox1.Text
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
Index = Array.IndexOf(Usernames, TextBox1.Text)
If TextBox2.Text = Passwords(Index) Then
Form3.Show()
Me.Hide()
End If
Else
MsgBox("The username or password is incorrect", MsgBoxStyle.Critical)
End If
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CurrName = TextBox1.Text
' *** Error (apparently) happens here ***
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
MsgBox("This username already exists!")
Else
ReDim Preserve Usernames(UBound(Usernames) + 1)
Usernames(UBound(Usernames)) = TextBox1.Text
ReDim Preserve Passwords(UBound(Passwords) + 1)
Passwords(UBound(Passwords)) = TextBox2.Text
End If
Next
End Sub
Private Function IfRepetition(ByRef Usernames() As String, CurrName As String, i As Integer) As Boolean
Dim j As Integer
'Checks for repetition of a username in the usernames array
IfRepetition = False
For j = 0 To (UBound(Usernames))
If Usernames(j) = CurrName Then
IfRepetition = True
Exit Function
End If
Next
End Function
End Class
The error you're getting is because UBound throws exception if the array is null.
Also using arrays for that isn't a good way, I recommend you use Dictionary for easier, shorter code.
Dim dic As New Dictionary(Of String, String) 'A new dictionary which handles usernames & passwords
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Login button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If Not dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it doesn't exist show error message and return ( don't continue )
MessageBox.Show("The username is incorrect")
Return
End If
If dic(TextBox1.Text) <> TextBox2.Text Then 'Validate entered username and password, if it's wrong show error message and return ( don't continue )
MessageBox.Show("The password is incorrect")
Return
End If
Form3.Show() 'If none of above error messages appear which means the entered username and password are correct, show Form3 and hide this form
Me.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'create account button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it exists show error message and return ( don't continue )
MessageBox.Show("This username already exists")
Return
End If
dic.Add(TextBox1.Text, TextBox2.Text) 'If none of above error messages which means it's okay to create this account, Add the username & password to the dictionary
End Sub

How to validate a null value in a maskedtextbox phone number input mask

I want to check for null values. using this code below. i am still getting values in the textbox. The values i am getting in the textbox are "( ) -"...
If Text_Phone.Text IsNot "" Then
If BuildSqlFlag = True Then
BuildSql = BuildSql & " AND " & "Phone = " & Text_Phone.Text
Else
BuildSql = "Phone = " & Text_Phone.Text
End If
BuildSqlFlag = True
End If
i am not exactly sure what is needed from my code to be changed to i even tried the following:
If Text_Phone.Text IsNot "( ) -" Then
But that was no help.
Set the TextMaskFormat to exclude prompt and literals.
Text_Phone.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals
MaskFormat Enumeration
Then when you do Text_Phone.Text it will be equal to "" if it's empty.
'Validate phone number in this format: 999-999-9999
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim phoneNumber As New Regex("\d{3}-\d{3}-\d{4}")
If phoneNumber.IsMatch(TextBox1.Text) Then
TextBox2.Text = "Valid phone number"
Else
TextBox2.Text = "Not Valid phone number"
End If
End Sub
End Class
'Validate phone number in this format (999)999-9999
Private Sub Button1_Click_1(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim phoneNumber As New Regex("\(\d{3}\)\d{3}-\d{4}")
If phoneNumber.IsMatch(TextBox1.Text) Then
TextBox2.Text = "Valid phone number"
Else
TextBox2.Text = "Not Valid phone number"
End If
End Sub

call sub to change USERname color

I want to change USERname color inside RitchTextBox, I am using this code below to call the SUB but all the text now in red?
UPDATE
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & "$ ")
box.SelectionColor = Color.Black
box.AppendText(txtSend)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click
' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text)
Try
If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then
MsgBox("wright a message!", "MsgBox")
Else
client = New TcpClient(txtPCIPadd.Text, 44444)
Dim writer As New StreamWriter(client.GetStream())
txttempmsg.Text = (txtSend.Text)
writer.Write(txtUsername.Text + " # " + txtSend.Text)
AddMessage(txtUsername.Text, txttempmsg.Text + vbCrLf)
'txtmsg.Text="You:" + txtmessage.Text)
writer.Flush()
txtSend.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
When you have a problem trying to get something to work in your program. It is easier to create a test example that you can then use to figure out what is happening without dealing with a lot of other variables in your larger program. In your case I created a VB Winforms app, added a RichTextBox, two TextBox's and a Button. By doing so I am able to show that the function is working.
Public Class Form1
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & " :") 'Note added colon
box.SelectionColor = Color.Black
box.AppendText(txtSend) 'Note changed variable name to parameter name
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddMessage(txtUsername.Text, txttempmsg.Text)
End Sub
End Class
Example:

How do you change the value in my.settings in a form when you enter numbers in a textbox in VB.Net

I was wondering if you could help me? My question is that, is there a way of changing the value in my.Settings in a form if you enter a number/decimal in a textbox and click a button and then update in the settings to be then changed in another from which is linked to my.Settings in a variable?!
Form 1:
Public Class frmConverter
Dim input As String
Dim result As Decimal
Dim EUR_Rate As Decimal = My.Settings.EUR_Rates
Dim USD_Rate As Decimal = 1.6
Dim JYP_Rate As Decimal = 179.65
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
input = txtInput.Text
Try
If ComboBox1.Text = "£" Then
Pounds()
ElseIf ComboBox1.Text = "€" Then
Euros()
ElseIf ComboBox1.Text = "$" Then
Dollars()
ElseIf ComboBox1.Text = "¥" Then
Yen()
End If
Catch es As Exception
MsgBox("Error!")
End Try
End Sub
Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
Me.Hide()
frmExchange.Show()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
txtInput.Text = ""
lblResult.Text = ""
End Sub
Function Pounds()
If ComboBox1.Text = "£" And ComboBox2.Text = "€" Then
result = (input * EUR_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "$" Then
result = (input * USD_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "¥" Then
result = (input * JYP_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
End If
Return 0
End Function
Form 2:
Public Class frmExchange
Private Sub frmExchange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
My.Settings.EUR_Rates = (txtinput.Text)
My.Settings.Save()
My.Settings.Reload()
End Sub
Public Sub SetNewRate(ByVal rate As Decimal)
txtinput.Text = rate.ToString
End Sub
Private Sub btnchange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnchange.Click
If ComboBox1.Text = "€" Then
My.Settings.USD_Rates = (txtinput.Text)
frmConverter.SetNewRate(txtinput.Text)
End If
End Sub
End class
It sounds like you are trying to use My.Settings as some sort of set of global reference variables. Thats not what they are for, not how they work and not what they are.
First, turn on Option Strict as it looks like it may be Off. This will store the decimal value of a textbox to a Settings variable which is defined as a Decimal:
My.Settings.USD_Rates = CDec(SomeTextBox.Text)
Thats all it will do. It wont save the value and it wont pass it around or share it with other forms and variables.
My.Settings.Save 'saves current settings to disk for next time
My.Settings.Reload 'Load settings from last time
This is all covered on MSDN. There is no linkage anywhere. If you have code in another form like this:
txtRate.Text = My.Settings.USD_Rates.ToString
txtRate will not automatically update when you post a new value to Settings. There are just values not Objects (see Value Types and Reference Types). To pass the new value to another form:
' in other form:
Public Sub SetNewRate(rate As Decimal)
' use the new value:
soemTextBox.Text = rate.ToString
End Sub
in form which gets the change:
Private Sub btnchangeRate(....
' save to settings which has nothing to do with passing the data
My.Settings.USD_Rates = CDec(RateTextBox.Text)
otherForm.SetNewRate(CDec(RateTextBox.Text))
End Sub
You may run into problems if you are using the default form instance, but that is a different problem.
You botched the instructions. The 2 procedures are supposed to go in 2 different forms - one to SEND the new value, one to RECEIVE the new value. With the edit and more complete picture, there is an easier way.
Private Sub btnSettings_Click(...) Handles btnSettings.Click
' rather than EMULATE a dialog, lets DO a dialog:
'Me.Hide()
'frmExchange.Show()
Using frm As New frmExchange ' the proper way to use a form
frm.ShowDialog
' Im guessing 'result' is the xchg rate var
result = CDec(frm.txtInput.Text)
End Using ' dispose of form, release resources
End Sub
In the other form
Private Sub btnchange_Click(....)
' do the normal stuff with Settings, if needed then:
Me.Hide
End Sub

Stuck on my Login Panel

It keeps returning null and I was hoping someone could clean it up for me and see if there is a simpler way to do this. I'm really wanting to start making my game.
Public Class frmLogin
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
Application.Exit()
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text
If File.Exists(FILE_NAME) Then
Me.lblExists.Text = "Username has already been created!"
Return
End If
If txtCUser.Text.Length < 3 Then
Me.lblExists.Text = "Must have atleast 3 characters."
Return
End If
Dim writeFile As StreamWriter = File.CreateText("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text)
writeFile.WriteLine("User: " + Me.txtCUser.Text) ' user
writeFile.WriteLine("Pass: " + Me.txtCPass.Text) ' pass
writeFile.WriteLine("-------------------")
writeFile.Close()
End Sub
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) = False Then
Using sr As New StreamReader("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return (sr.ReadLine())
sr.Close()
End Using
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text
If File.Exists(FILE_NAME) And Me.txtPassword.Text = (GetLine(FILE_NAME, 2).Substring(6)) Then
Me.lblLoggedIn.Text = "Logged"
ElseIf File.Exists(FILE_NAME) = False Then
Me.lblLoggedIn.Text = "You must create an account! Navigate to TabPage2."
End If
End Sub
End Class
It would really help a lot. I just started vb not to long ago maybe about a week or two.
Three things. First, in GetLine() you're attempting to open the file if it does NOT exist; change from False to True. Second, you should open the file name that was passed in, not a hard-coded one that uses the value from a TextBox. Lastly, to get rid of the warning, you need to return something if the file does not exist:
Change GetLine() to:
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) Then
Using sr As New StreamReader(fileName)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return sr.ReadLine()
End Using
Else
Return "{File Not Found: " & fileName & "}"
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
*You were returning the exception as a string, so I followed that model with the file not found error. How will you know, though, if you have an actual error, or if the line in the file was exactly like the "error" being returned?