Multiple validation in vb.net textbox - vb.net

The problem i am having is after checking if the field is blank i want program to stop at that, right now it is going ahead and checking the username password also even though the field is blank and printing wrong username password. i am really new at this so please excuse the lack of knowledge
Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
Try
Dim con As New SqlConnection("Initial Catalog=stock;Data source=.;integrated security=true")
Dim ds1 As New DataSet
Dim da1 As New SqlDataAdapter("select * from login where Name='" & Trim(txtusername.Text) & "'and password='" & Trim(txtpassword.Text) & "'", con)
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
End If
If da1.Fill(ds1) Then
adminmain.Show()
Me.Close()
Else
MsgBox("Invalid Password or Username")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Then Return from the function.
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
Return
End If
But outside of the Try/Catch although it would work(a finally-block would be executed before the return statement). Actually the validation of the TextBox does not need to be inside of the Try/Catch, so imho it's confusing to return from within a Try/Catch.

Put your validations at the top of the Sub, and call Exit Sub as soon as an error is found.
Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
Exit Sub
End If
'Other validations here
'Code to save changes here
End Sub
Also, you should remove that Try..Catch clause. If an unexpected error occurs you'll want to know what is the line number and stack trace of the error.

Related

why does the progress bar not working when button insert is click in vb.net

I'm creating an insert button that will save records from list view to mysql database. When user clicked the insert button, the progress bar will show the progress until the records are inserted. The problem is, the progress bar only start after the insert task have been done.
This for vb.net, running mysql database. In the past, I've tried using countdown number and it also does not work.
'load form code
Private Sub formDevice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Refresh()
Timer2.Enabled = False
End Sub
'insert button
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Try
Timer2.Enable = True
Timer2.Start()
Dim form As New editDevice
form.lblName.Text = DataGridView1.CurrentRow.Cells(0).Value.ToString()
For Each item As ListViewItem In lvLogs.Items
Dim insert_command As New MySqlCommand("INSERT INTO fingerprint(Enroll_no,Date_time,device_name)" & _
"VALUES (#Enroll_no,#Date_time,#device_name)", connection)
insert_command.Parameters.AddWithValue("#Enroll_no", item.SubItems(1).Text)
insert_command.Parameters.AddWithValue("#Date_time", item.SubItems(4).Text)
insert_command.Parameters.Add("#device_name", MySqlDbType.UInt32).Value = form.lblName.Text
connection.Open()
If insert_command.ExecuteNonQuery() = 1 Then
Else
MessageBox.Show("Error")
End If
connection.Close()
Next
MessageBox.Show("Insert done")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
'timer code
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
ProgressBar1.Increment(10)
If ProgressBar1.Value = 100 Then
Timer2.Stop()
End If
End Sub
I expect the progress bar will run when the insert button is clicked
You can try to add an Application.DoEvents call within your for loop
For Each item As ListViewItem In lvLogs.Items
Dim insert_command As New MySqlCommand("INSERT INTO fingerprint(Enroll_no,Date_time,device_name)" & _
"VALUES (#Enroll_no,#Date_time,#device_name)", connection)
insert_command.Parameters.AddWithValue("#Enroll_no", item.SubItems(1).Text)
insert_command.Parameters.AddWithValue("#Date_time", item.SubItems(4).Text)
insert_command.Parameters.Add("#device_name", MySqlDbType.UInt32).Value = form.lblName.Text
connection.Open()
If insert_command.ExecuteNonQuery() = 1 Then
Else
MessageBox.Show("Error")
End If
connection.Close()
Application.DoEvents()
Next
This lets your UI update (and other events be triggered) once in between each item processed.
Forget the timer and progress bar for a while and just get your data entry code running smoothly.
Since you never show form, it is useless to fill a label on it. Just assign the value of the grid cell to the parameter.
Keep your data objects local so you can ensure that they are closed and disposed. Using...End Using blocks will do this for you even if there is an error.
Do not create a new command and parameters in the loop. The only thing that changes on each iteration is the value of 2 of the parameters.
Do not use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
I had to guess at the datatypes and sizes. Check you database for actual types and sizes.
Unless your connection to MySql is very slow or you have a huge number of items in your list view, you may not need a progress bar. If you do then refer to #jmcilhinney comment.
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Try
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand("INSERT INTO fingerprint(Enroll_no,Date_time,device_name) VALUES (#Enroll_no,#Date_time,#device_name);", cn)
cmd.Parameters.Add("#Enroll_no", MySqlDbType.VarChar, 100)
cmd.Parameters.Add("#Date_time", MySqlDbType.DateTime)
cmd.Parameters.Add("#device_name", MySqlDbType.UInt32).Value = DataGridView1.CurrentRow.Cells(0).Value.ToString()
cn.Open()
Dim d As DateTime
For Each item As ListViewItem In lvLogs.Items
DateTime.TryParse(item.SubItems(4).Text, d)
cmd.Parameters("#Enroll_no").Value = item.SubItems(1).Text
cmd.Parameters("#Date_time").Value = d
cmd.ExecuteNonQuery()
Next
End Using
End Using
MessageBox.Show("Insert done")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

vb.net login with sqlite

im trying to create a login form in vb.net with SQLite with this code
Imports System.Data.SQLite
Public Class frmLogin
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim table As DataTable = Nothing
Dim da As New SQLiteDataAdapter("Select * from user_tbl where username='" & txtuser.Text & "'and pass_id='" & txtpass.Text & "'", myconn)
Try
If txtuser.Text = "" And txtpass.Text = "" Then
MessageBox.Show("Please fill Username and Password", "Important", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtuser.Focus()
Else
da.Fill(table)
If table.Rows.Count > 0 Then
frmMain.Show()
Me.Close()
Else
MessageBox.Show("login not successful")
End If
da.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ConnectME()
End Sub
End Class
but i keep getting an error at line 26 "da.fill(table)"
Here is what the error says:
Here are two lines of your code:
Dim table As DataTable = Nothing
da.Fill(table)
You have no code in between that assigns an object to that table variable. Why exactly are you surprised that there's an issue here? If I told you to fill a bag and then handed you no bag, how exactly would you go about filling it? You couldn't, because you can't fill a bag that doesn't exist, yet you expect your app to be able to fill a DataTable that doesn't exist.

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

How to run a code that executes in accidental closing of the program in VB.net

This is my code in executing a code that will set the status of a user to offline if they properly close the program:
Private Sub frmMainForm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If MsgBox("Are you sure you want to exit this application?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Exit?") = MsgBoxResult.Yes Then
Update_UserStatus(iUserID, 0) 'update the Status of user to Offline
End
End If
e.Cancel = True
End Sub
Public Sub Update_UserStatus(iUserID As Integer, isOnline As Integer)
Dim strQ As String = String.Empty
strQ = "update tbl_user set isOnline = " & isOnline & " where ID = " & iUserID & ""
Try
If con.State = ConnectionState.Closed Then con.Open()
cmd = New MySqlCommand(strQ, con)
cmd.ExecuteNonQuery()
cmd = Nothing
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
But how can I run this code when the program accidentally close, for example when I open the task manager and force to close the program there. Thank you in advance
You can handle the application threadexception event
Public Shared Sub Main()
' Add the event handler for handling UI thread exceptions to the event.
AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
Private Shared Sub Form1_UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
Dim result As System.Windows.Forms.DialogResult = _
System.Windows.Forms.DialogResult.Cancel
Try
result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception)
Catch
Try
MessageBox.Show("Fatal Windows Forms Error", _
"Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
Finally
Application.Exit()
End Try
End Try
' Exits the program when the user clicks Abort.
If result = DialogResult.Abort Then
Application.Exit()
End If
End Sub
here you can find a Source Code about how to use it

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