Why does loop doesnt stop at .showdialog in formloadevent - vb.net

Hello here is a very strange bug I cannot solve. I have a while loop in my formload that looks this way :
While loginOK = False And pstop = False
LoginForm1.ShowDialog()
If NewReg = True Then
While RegErfolgreich = False
Registrierung.ShowDialog()
Dim con As New SqlConnection(My.Settings.SLXADRIUMDEVConnectionString)
con.Open()
Dim cmd = New SqlCommand("Insert Into sysdba.PL_Userverwaltung (Benutzername, Passwort, [E-Mail-Adresse], Profil_OK) Values('" & RegBenutzername & "', '" & RegPassword & "', '" & RegEMailAdresse & "', 'f')", con)
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
End If
End While
Else
NewReg = False
End If
End While
The problem is that after closing loginform1 he jumps back in the loop, and when he starts looping again he opens loginform1 and closes it instantly. and loops again in the while loop.
That means I have a endless loop, which shows the loginform1 and closes it a millisecond later.
One thing to mention is that a friend of mine opened my project in an older vs studio version and this mysterious bug doesnt happen??
Hope for input cheers
EDIT:
Here is loginform1 code
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
Startseite.LoginUsername = UsernameTextBox.Text
Startseite.LoginPassword = PasswordTextBox.Text
Startseite.loginOK = True
Me.Close()
Else
MsgBox("Bitte Benutzername und Passwort eingeben!")
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Startseite.pstop = True
Me.Close()
End Sub
Private Sub LoginForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.Benutzername <> "" And My.Settings.Passwort <> "" Then
'MsgBox(My.Settings.Benutzername & " " & My.Settings.Passwort)
UsernameTextBox.Text = My.Settings.Benutzername
PasswordTextBox.Text = My.Settings.Passwort
End If
End Sub
Private Sub lblNeuRegistrieren_Click(sender As Object, e As EventArgs) Handles lblNeuRegistrieren.Click
Startseite.NewReg = True
Me.Close()
End Sub

About your error, probably you didn't initialize your startseite variable to be your main form, loginOK And pstop never get changed and that's why the loop never stops. But on the rest of your code, some general tips.
This is unnecesary
If NewReg = True Then
''
Else
NewReg = False
End If
If NewReg is not true, then it's false by definition. Should be
If NewReg Then
''
End If
Also, overloading the showDialog on loginForm1 is a better solution than adding a yourmainclass object on the second form. It is easier to debug and provides better reusability.

try exiting loop on message box
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
Exit While
End If

Related

How to Auto Open or refresh or reload my Form when the date i set in reminders the same with the date in my computer?

I made a program Reminder System that Auto send email when the date i set in my apps much the date in my computer. the problem is i need to restart my apps so that the reminder will show or the form will be loaded. if not it will not alert. so i need your help guys if the date change in my computer my apps will auto reload or refresh so that if have reminders it will be send to email. btw my program will be installed in a server that will always be open so i just need to auto reload my form every time the date change. below is my code in setting the reminders.
Imports System.IO
Public Class Reminder
Dim m As MsgBoxResult
Dim t As String
Private Sub Reminder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = TimeOfDay.ToString("h:mm:ss tt")
Dim m1 As MsgBoxResult
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
If Date.Today = MonthCalendar1.TodayDate And File.Exists(t & ".txt") = True Then
m1 = MsgBox("You set a reminders for today. Would you like to send to EMAIL ?", MsgBoxStyle.YesNo)
If m1 = MsgBoxResult.Yes Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
Notetxt.Text = File.ReadAllText(t & ".txt")
sendEmail.Show()
sendEmail.emailtxt.Text = Notetxt.Text
sendEmail.Hide()
MsgBox("SEND EMAIL SUCCESSFUL", vbOKOnly)
lblMessage.Hide()
End If
End If
End Sub
Private Sub MonthCalendar1_DateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles MonthCalendar1.DateChanged
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
Try
If File.Exists(t & ".txt") = True Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Notetxt.Text = File.ReadAllText(t & ".txt")
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
lblMessage.Hide()
Else
m = MsgBox("Would you like to enter a reminders for this date?", MsgBoxStyle.YesNo)
If m = MsgBoxResult.Yes Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
Notetxt.Text = ""
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
lblMessage.Hide()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Backbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Backbtn.Click
Notetxt.Enabled = False
Notetxt.Hide()
MonthCalendar1.Enabled = True
MonthCalendar1.Show()
SaveBtn.Hide()
Addbtn.Hide()
delbtn.Hide()
Backbtn.Hide()
lblMessage.Show()
End Sub
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
Try
If Notetxt.Text = "" Then
If File.Exists(t & ".txt") = True Then
File.Delete(t & ".txt")
End If
End If
If Notetxt.Text.Length > 0 Then
File.WriteAllText(t & ".txt", Notetxt.Text)
MsgBox("SAVE SUCCESS", vbOKOnly)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Addbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Addbtn.Click
Notetxt.Text = "Hi QC Engineer, Golden Sample meet Due date already please change." & Environment.NewLine & "MODEL: " & Environment.NewLine & "START DATE: " & Environment.NewLine & "DUE DATE: " & Environment.NewLine & "APPROVED BY: EAKKACHAI"
End Sub
Private Sub delbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delbtn.Click
Notetxt.Clear()
File.Delete(t & ".txt")
End Sub
End Class
and below is my code for sending email.
Public Class sendEmail
Private Sub sendEmail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Content As String
Content = emailtxt.Text
emailtxt.Text = Reminder.Notetxt.Text
Dim Outlook As New Microsoft.Office.Interop.Outlook.Application
Dim MailItem As Microsoft.Office.Interop.Outlook.MailItem
MailItem = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
With MailItem
.HTMLBody = emailtxt.Text
.Subject = "GOLDEN SAMPLE DUE DATE EXPIRED"
'use the below to change from the default email account
.SentOnBehalfOfName = "your#email.com"
'you can add multiple recipients using .Add()
.Recipients.Add("your#email.com")
'examples of other optional arguments that can be included
' .Attachments.Add([file])
.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh
.Send() 'opens the email for checking prior to sending or use .Send()
End With
End Sub
End Class

Multiple Definition with Identical Signatures

Dim WithEvents client As New WebClient
Private Sub DirectX9ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DirectX9ToolStripMenuItem.Click
Try
client.DownloadFileAsync(New Uri("http://download1588.mediafire.com/y9phz64wph4g/aqlp1m71mvuwo74/Direct+X+11+Update.rar"), "C:\Documents and Settings\All Users\Documents\Direct X 11 Update.RAR")
Catch ex As Exception
MsgBox("File already exists or is corrupted!")
End Try
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles client.DownloadFileCompleted
MsgBox("Direct X 9 has been successfully downloaded!", MsgBoxStyle.Information)
Label48.Visible = False
Label49.Visible = False
ProgressBar3.Visible = False
Label48.Text = "0 &"
Label49.Text = "0 / 0"
ProgressBar3.Value = 0
End Sub
Private Sub client_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles client.DownloadProgressChanged
Label48.Visible = True
Label49.Visible = True
ProgressBar3.Visible = True
Label48.Text = ProgressBar3.Value & "%"
Label49.Text = e.BytesReceived & " / " & e.TotalBytesToReceive
ProgressBar3.Value = e.ProgressPercentage
End Sub
Private Sub GeForceExperienceV2000ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GeForceExperienceV2000ToolStripMenuItem.Click
Try
client.DownloadFileAsync(New Uri("http://download903.mediafire.com/w91mlqdf6clg/a540a35f5ddcpbn/GeForce_Experience_v2.2.2.0.exe"), "C:\Documents and Settings\All Users\Documents\GeForce_Experience_v2.2.2.0.exe")
Catch ex As Exception
MsgBox("File already exists or is corrupted!")
End Try
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles client.DownloadFileCompleted
MsgBox("GeForce_Experience_v2.2.2.0 has been successfully downloaded!", MsgBoxStyle.Information)
Label48.Visible = False
Label49.Visible = False
ProgressBar3.Visible = False
Label48.Text = "0 &"
Label49.Text = "0 / 0"
ProgressBar3.Value = 0
End Sub
End Class
You got your answer in comments but just going to explain to make sure you understand what you can and can't do.
When you create a method you name it so that when you call it your program knows which one it is you want to call. When you name 2 methods the same way it does not know which one to use when it is called.
The only way to have 2 methods with the same name is if they have a different "signature" that means it can't be 100% identical. Different parameters will make your method's signature different even if they are called the same

Please complete required fields message box

I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted

Why is my form disappearing when I press ENTER?

Good-day,
I'm experiencing a very strange event that just started happening. Whenever I press the ENTER button on my keyboard, I expect the KeyDown event of my textbox to be raised and the corresponding code run. Instead, the form disappears (as if the .Hide() method has been called). When I debug, I see that the code that's supposed to run after the KeyDown event is raised is executing accordingly - but the form just disappears.
I've never encountered this before, so I don't know what to do. Any help would be appreciated. Thanks.
HERE'S THE CODE OF MY FORM:
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class FormAdd
#Region "VARIABLE DECLARATIONS CODE"
'FOR MySQL DATABASE USE
Public dbConn As MySqlConnection
'FOR CARD NUMBER FORMATTING
Private CF As New CardFormatter
'FOR CARD ENCRYPTION
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encryptedCard As String
#End Region
#Region "SUB-ROUTINES AND FUNCTIONS"
Private Sub GetDBdata()
Try
If TextBoxAccount.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxAccount.Focus()
Else
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
If dbTable.Rows.Count > 0 Then
'MessageBox.Show("Customer Account Found!")
Call recordFound()
TextBoxLastName.Text = dbTable.Rows(0).Item("nameLAST")
TextBoxFirstName.Text = dbTable.Rows(0).Item("nameFIRST")
TextBoxSalutation.Text = dbTable.Rows(0).Item("nameSALUTATION")
TextBoxCompanyName.Text = dbTable.Rows(0).Item("nameCOMPANY")
Else
'MessageBox.Show("No Customer Records Found! Please try again!")
Call recordNotFound()
ButtonReset.PerformClick()
End If
dbConn.Close()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub SetDBData()
Try
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim noCard As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM cc_master WHERE ccNumber = '" & TextBoxCard.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows() = True Then
MessageBox.Show("This Credit/Debit Card Already Exists! Try Another!")
noCard = False
Else
noCard = True
End If
End While
dbData.Close()
If noCard = True Then
'PERFORM CARD ENCRYPTION
'PERFORM DATABASE SUBMISSION
Dim dbQuery2 As String = "INSERT INTO cc_master (ccType, ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, customer_accountNumber)" & _
"VALUES('" & ComboBoxCardType.SelectedItem & "','" & TextBoxCard.Text & "','" & TextBoxExpireMonth.Text & "','" & TextBoxExpireYear.Text & _
"','" & TextBoxZipCode.Text & "','" & TextBoxCVV2.Text & "','" & Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & TextBoxAccount.Text & "');"
Dim dbData2 As MySqlDataReader
Dim dbAdapter2 As New MySqlDataAdapter
Dim dbCmd2 As New MySqlCommand
dbCmd2.CommandText = dbQuery2
dbCmd2.Connection = dbConn
dbAdapter2.SelectCommand = dbCmd2
dbData2 = dbCmd2.ExecuteReader
MessageBox.Show("Credit/Debit Card Information Saved SUCCESSFULLY!")
ButtonReset.PerformClick()
End If
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub ResetForm()
TextBoxAccount.Clear()
TextBoxLastName.Clear()
TextBoxFirstName.Clear()
TextBoxSalutation.Clear()
TextBoxCard.Clear()
ComboBoxCardType.SelectedItem = ""
TextBoxCompanyName.Clear()
TextBoxCVV2.Clear()
TextBoxExpireMonth.Clear()
TextBoxExpireYear.Clear()
TextBoxZipCode.Clear()
CheckBoxConfirm.Checked = False
TextBoxAccount.SelectionStart = 0
TextBoxAccount.SelectionLength = Len(TextBoxAccount.Text)
TextBoxAccount.Focus()
GroupBoxInputError.Hide()
LabelInstruction.Show()
GroupBox1.Height = 75
End Sub
Private Sub recordFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Green
LabelError.ForeColor = Color.White
LabelError.Text = "RECORD FOUND!"
GroupBoxInputError.Visible = True
GroupBox1.Height = 345
ButtonReset.Show()
LabelInstruction.Hide()
ComboBoxCardType.Focus()
End Sub
Private Sub recordNotFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Red
LabelError.ForeColor = Color.White
LabelError.Text = "NO RECORD FOUND!"
GroupBoxInputError.Visible = True
End Sub
'Public Sub encryptCard()
' Try
' DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
' DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
' Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxCard.Text)
' TextBoxCard.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
' Catch ex As Exception
' MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "TOOLSTRIP MENU CONTROL CODE"
Private Sub ExitAltF4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitAltF4ToolStripMenuItem.Click
End
End Sub
#End Region
#Region "BUTTON CONTROLS CODE"
Private Sub ButtonExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExit.Click
FormMain.Show()
Me.Close()
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
Call ResetForm()
End Sub
Private Sub ButtonSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click
Call SetDBData()
Call ResetForm()
End Sub
Private Sub ButtonEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles ButtonEncrypt.Click
End Sub
#End Region
#Region "FORM CONTROLS CODE"
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
TextBoxAccount.Focus()
Me.KeyPreview = True
Timer1.Enabled = True
Timer1.Interval = 1
GroupBoxInputError.Hide()
ButtonSubmit.Hide()
ButtonReset.Hide()
GroupBox1.Height = 75
'LabelFooter.Text = "Welcome " & FormLogin.TextBoxUsername.Text() & " | Timestamp: " & Date.Now.ToString
Try
LabelIP.Text = "IP: " & Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString
Catch ex As Exception
End Try
'Populate the Card Type combobox with the list of card types from the CardFormatter class
ComboBoxCardType.Items.AddRange(CF.GetCardNames.ToArray)
End Sub
#End Region
#Region "TEXTBOX CONTROLS CODE"
Private Sub TextBoxCard_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.GotFocus
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
Me.Refresh()
End Sub
Private Sub TextBoxCard_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.LostFocus
'//CARD VALIDATION//
' This code will check whether the card is a valid number or not. It doesn't check to see if the card is active.
' The code calls on the creditcard function stored in MyModules.vb
Try
If creditcard(TextBoxCard.Text) Then
'MsgBox("Card is Valid")
TextBoxCard.BackColor = Color.GreenYellow
TextBoxCard.ForeColor = Color.Black
GroupBoxInputError.Visible = False
TextBoxCard.Text = CF.GetFormattedString(ComboBoxCardType.Text, TextBoxCard.Text)
Me.Refresh()
Else
BWErrorNotice.RunWorkerAsync()
'MsgBox("Invalid Card")
GroupBoxInputError.Visible = True
TextBoxCard.Focus()
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBoxAccount_GotFocus(sender As Object, e As System.EventArgs) Handles TextBoxAccount.GotFocus
TextBoxAccount.SelectAll()
End Sub
Private Sub TextBoxAccount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAccount.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
If TextBoxAccount.Text <> "" Then
Call GetDBdata()
Else
MsgBox("You must enter an account number!", MsgBoxStyle.Exclamation, "ATTENTION PLEASE!")
TextBoxAccount.Focus()
End If
End If
'If e.KeyCode = Keys.Enter Then
' e.Handled = True
' SendKeys.Send("{Tab}")
'End If
End Sub
Private Sub TextBoxCard_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBoxCard.MouseClick
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End Sub
#End Region
#Region "OTHER/MISCELLANEOUS CONTROLS CODE"
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LabelDateTime.Text = DateTime.Now
End Sub
Private Sub BWErrorNotice_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWErrorNotice.DoWork
Do While Not creditcard(TextBoxCard.Text)
LabelError.BackColor = Color.Black
System.Threading.Thread.Sleep(500)
LabelError.BackColor = Color.Red
System.Threading.Thread.Sleep(500)
Loop
BWErrorNotice.CancelAsync()
End Sub
Private Sub CheckBoxConfirm_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxConfirm.CheckedChanged
If CheckBoxConfirm.Checked = True Then
ButtonSubmit.Show()
Else
ButtonSubmit.Hide()
End If
End Sub
#End Region
End Class
Although what follows will not likely solve the form disappearance problem, it will resolve a downstream issue:
In GetDBData(), you are assigning accountNumber to the value of TextBoxAcount.Text, which must be enclosed with quotes unless you employ a parameter which I strongly recommend you get in the habit of doing.
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Parameters offer a number of benefits including implicit type conversions, injection attack prevention, and will sometimes even cure unexpected behaviors.
I figured out the problem. I was calling Dispose() at the end of my GetDBData() function - so the form was getting disposed before execution returned back to the TextBox. I deleted it and all is well again.

Issue Log in vb.Net?

I have a problem with a log in... Well let me explain you my problem, the problem is that i want to create a log in with restrictions, I have some textbox with the binding source property changed to my database. But when I type something that is not in the DataBase the program got freezes, I will post my code, hope you can help me (=
Private Sub KryptonButton1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles KryptonButton1.Click
If txtUser.Text <> UserTextBox.Text Then
While txtUser.Text <> UserTextBox.Text
Me.UsuarioContraseñaBindingSource.MoveNext()
End While
If txtUser.Text = UserTextBox.Text Then
KryptonMessageBox.Show("Welcome")
Else
KryptonMessageBox.Show("Error")
End If
End If
End Sub
Have a closer look at the loop in your code and its exit condition … under what circumstances does the loop exit? What happens otherwise?
In general you need play out and cover all scenarios but you already know the scenario here: your user input is not in the database and the application freezes. This should provide ample hints to find the cause.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If txt_user.Text <> vbNullString And txt_pass.Text <> vbNullString Then
Dim chkcmd As New SqlCommand("select * from users where username = '" & txt_user.Text & "' and password = '" & txt_pass.Text & "'", con)
If con.State = ConnectionState.Open Then con.Close()
con.Open()
Dim chkval As SqlDataReader = chkcmd.ExecuteReader
If chkval.Read = True Then
Me.Hide()
Form2.Show()
Else
MsgBox("Invalid key to login!", MsgBoxStyle.Exclamation, "Message")
txt_pass.Clear()
txt_user.Clear()
txt_user.Select()
End If
con.Close()
End If
End Sub