vb.net login with sqlite - vb.net

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.

Related

refresh button for datagridview

i need help in refresh the datagridview. I create a Update button and show button but it didn't refresh. but i check in my database access it update successful
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Public con As OleDbConnection
Public da As OleDbDataAdapter
Public ds As New DataSet
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Dim count As Integer = 100
Dim ID As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'Establish connection
con = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\m_j_g\Documents\Visual Studio 2010\Projects\DatabaseApplication\Department.accdb")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
'establish connection
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
'execute sql query
da = New OleDbDataAdapter("Select * from table1", con)
'Fill Dataset
da.Fill(ds, "table1")
'put data from dataset to datagridview
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
Try
con.Open()
cmd = New OleDbCommand("Update table1 set SurName='" & TextBox2.Text & "', FirstName='" & TextBox3.Text & "' where EmailAddress='" & TextBox5.Text & "'", con)
'Execute UPDATE Query
cmd.ExecuteNonQuery()
MsgBox("Record Updated Successfully..." & Chr(13) & "Email Address: " & TextBox5.Text & Chr(13) & "SurName: " & TextBox2.Text & Chr(13) & "FirstName: " & TextBox3.Text)
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am newbie in programming Thank you for your help
You need to rebind the Grid after performing the update, Follow these steps this may help you:
Define a Method for binding the giridiew, this will populate the grid with values from the DB:
Public Sub bindMyGrid()
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
da = New OleDbDataAdapter("Select * from table1", con)
da.Fill(ds, "table1")
DataGridView1.Rows.Clear() '<-- new line added
DataGridView1.DataSource = ds.Tables(0)
End Sub
Call the method in the click event of the show button to populate the grid:
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
bindMyGrid()
Catch ex As Exception
' handle error here
End Try
End Sub
Perform the update operation on update button click, and call the method again to get the latest values.
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
Try
'Perform the update operations here
' Call bindMyGrid() to rebind the grid
bindMyGrid() 'this will populate the new value to the grid.
Catch ex As Exception
'Handle error here
End Try
End Sub

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

My Picture box is not giving the output of an image

Help my code is not running but its catching my error message, I want to show the images from my database and i will pass it to my picture box
'This is my code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsearch.Click
Try
disconnect()
connect()
cmd = New Odbc.OdbcCommand("Select * FROM tblemployee WHERE lname ='" & Trim(TextBox1.Text.TrimEnd()) & "'", con)
dr = cmd.ExecuteReader
If dr.Read() Then
PictureBox1.Image = (dr("emp_pix"))
Else
MessageBox.Show("No Information Record, Please Name!")
End If
Catch ex As Exception
Debug.WriteLine("Please try again" & ex.Message)
End Try
End Sub
You can't display directly byte as Image. you need to convert it and display it.
Try like this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsearch.Click
Try
disconnect()
connect()
cmd = New Odbc.OdbcCommand("Select * FROM tblemployee WHERE lname ='" & Trim(TextBox1.Text.TrimEnd()) & "'", con)
dr = cmd.ExecuteReader
If dr.Read() Then
Dim bytBLOBData() As Byte = dr("emp_pix")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox1.Image = Image.FromStream(stmBLOBData)
Else
MessageBox.Show("No Information Record, Please Name!")
End If
Catch ex As Exception
Debug.WriteLine("Please try again" & ex.Message)
End Try
End Sub

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

Multiple validation in vb.net textbox

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.