login form using ms access in vb.net - vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?

You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions

I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html

You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.

Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc

here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class

Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub

Related

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

Inserting combo box values?

I'm trying to get my system to insert combo box values into my access database. I always get this very long error whenever I try to click my 'add' button and I somehow get this feeling that it's because of my INSERT statement. This is my whole code for my form. Any help will be greatly appreciated! Thank you
Imports System.Data.OleDb
Public Class AdmMain
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.txtFName.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
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\Database1.accdb"
conn.Open()
Dim sqlquery As String = "INSERT INTO students (StudentID, FirstName,MiddleName,LastName,Yr, Section) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
Dim SqlCommand As New System.Data.OleDb.OleDbCommand
SqlCommand.Parameters.AddWithValue("#studid", TxtID.Text)
SqlCommand.Parameters.AddWithValue("#fname", txtFName.Text)
SqlCommand.Parameters.AddWithValue("#mname", txtMName.Text)
SqlCommand.Parameters.AddWithValue("#lname", txtLName.Text)
SqlCommand.Parameters.AddWithValue("#yr", rbdtext)
SqlCommand.Parameters.AddWithValue("#sec", uno)
SqlCommand.Connection = conn
Dim sqlRead As System.Data.OleDb.OleDbDataReader = SqlCommand.ExecuteReader()
MsgBox("One record successfully added!", "Added!")
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Heres the error the keeps showing btw!
http://i.imgur.com/DgjiWqm.png
It looks like you are never assigning a select statement to SqlCommand inside your btnAdd_Click method. Try adding SqlCommand.CommandText = sqlquery.
You need to change your query in this way
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlQuery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#studid", TxtID.Text)
cmd.Parameters.AddWithValue("#fname", txtFName.Text)
cmd.Parameters.AddWithValue("#mname", txtMName.Text)
cmd.Parameters.AddWithValue("#lname", txtLName.Text)
cmd.Parameters.AddWithValue("#yr", rbdtext)
cmd.Parameters.AddWithValue("#sec", uno)
Dim rowsInserted = cmd.ExecuteNonQuery()
if rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
else
MessageBox.Show("Failure to add new record!", "Failure!")
End if
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
I have changed the name of your OleDbCommand object to avoid unnecessary confusion with the class SqlCommand used in SqlClient namespace (Not strictly necessary but nevertheless confusing when reading your code). Then I have used the OleDbCommand constructor that gets both the command text and the connection to be used by your command. This avoids to forget setting these essential properties, finally SECTION is a reserved keyword for MS-Access, thus, when used in query text, you need to encapsulate it between square brackets otherwise you get a SYNTAX ERROR

How to read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms?

This is my first question, by the way - and I'm not sure exactly how to ask, or say what's wrong. There's 3 things I can't sort so any help would be appreciated.
Module:
This and the first (login) form work as they are but I couldn't get either Form to reference con.connectionstring for them to use without having to re-use the string contained in "" (as they do below) - my attempts ended up with errors including saying that the state couldn't be changed as the connection was already open, but I'd like the same one string to be referenced from the Forms.
Module ConnectionModule
Public con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Public da As OleDb.OleDbDataAdapter
Public ds As DataSet = New DataSet
Public Path As String = Application.StartupPath
Public Sub OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
con.Open()
If con.State = ConnectionState.Closed Then
MsgBox("Connection to db not made.")
End If
End Sub
Public CurrentUser As String = Nothing
End Module
The First Form:
Public Class LoginForm
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OpenDb()
con.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ID As String = txtID.Text
Dim Pass As String = txtPassword.Text
If IsNumeric(ID) = False Or ID.Length > 4 Or Pass = Nothing Then
MsgBox("Staff ID is a 4-digit number and Password must not be blank.")
Else
Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
con.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then 'Correct:
MenuForm.Show()
Me.Hide()
CurrentUser = ID
Else 'Incorrect:
MsgBox("Staff ID or Password incorrect.")
txtPassword.Text = ""
txtID.Text = ""
txtID.Focus()
End If
Catch ex As Exception
MsgBox("Database Connection Error.")
End Try
con.Close()
End If
End Sub
End Class
A form to change the password:
The problem here is that lblUser (A clarification for the user to tell them which password will be changed) only outputs the data already within the program as a variable: CurrentUser (as assigned upon successful login). No error is produced but the full name of the user isn't shown (or possibly read from the database).
I'm also unsure how the UPDATE SQL command should be contained within the second procedure, btnAccept_click, here. What the syntax is, basically. I haven't found a clear example to look at.
Imports System.Data.OleDb
Public Class PasswordForm
Private Sub PasswordForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New System.Data.OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Dim Returned(2) As String
CurrentUser = CurrentUser
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Title], [Forename], [Surname] FROM tblStaff WHERE [StaffID]='" & CurrentUser & "'", con)
Try
con.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
'Makes db contents variables
Returned(0) = reader.Item("[Title]").ToString
Returned(1) = reader.Item("[Forename]").ToString
Returned(2) = reader.Item("[Surname]").ToString
End If
reader.Close()
Catch ex As Exception
Me.Hide()
MsgBox("Database Connection Error.")
Finally
con.Close()
End Try
lblUser.Text = "Current User: " & CurrentUser & Returned(0) & Returned(1) & Returned(2)
''Only outputs CurrentUser
End Sub
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccept.Click
Dim Current As String = txtCurrent.text
Dim NewPass As String = txtNew.Text
'Verification
If txtNew.Text = txtConfirm.Text And NewPass.Length <= 20 Then
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE tblStaff SET [Pword]='" & NewPass & "' WHERE [StaffID]='" & CurrentUser & "'", con)
End If
End Sub
End Class
Thank you, again, for anyone with ideas (especially exact code).
Oh and throughout what's here there are no errors thrown. Just missing content.
you are opening the connection in openDB() and you are trying to open it again in form1, this will throw the error you are getting. So comment all the con related lines in your form. Same comment for your passowrd form also.
'Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
'con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
'con.Open()
...
end try

How to simultaneously update an Access table and a DataGridView control?

I have a .NET application, where some of its methods updates Access database tables.
My problem is the DataGridView control that displays data, is not updating.
To do it, I have to restart the application, which is not something I desire.
Public Class frmUsers
Dim cnn3 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
Dim sql2 As String
Dim ds1 As New DataSet
Dim adptr As OleDbDataAdapter
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim Command1 As New OleDbCommand
Dim i2 As Integer
Dim sql1 As String
Dim Status As String
Try
Dim cnn3 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
cnn3.Open()
If ComboBox1.SelectedValue = "Admin" Then
Status = "Admin"
Else
Status = "Student"
End If
sql1 = "INSERT INTO Users ([ID],[PASSWORD],[LASTNAME],[FIRSTNAME],[LOGINTYPE]) VALUES('" & txtUID.Text & "','" & txtUPassword.Text & "','" & txtULastname.Text & "','" & txtUFirstName.Text & "','" & Status & "')"
Command1 = New OleDbCommand(sql1, cnn3)
i2 = Command1.ExecuteNonQuery
MessageBox.Show("Users Added Successfull")
Catch ex As Exception
End Try
End Sub
Private Sub btnback_Click(sender As Object, e As EventArgs) Handles btnback.Click
Me.Hide()
frmFaculty.Show()
End Sub
Private Sub frmUsers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cnn4 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
sql2 = "Select * from Users"
Try
cnn4.Open()
adptr = New OleDbDataAdapter(sql2, cnn4)
adptr.Fill(ds1)
DataGridView1.DataSource = ds1.Tables(0)
Catch ex As Exception
End Try
cnn4.Close()
End Sub
End Class
You need to update it mannually.
Try this:
Dim cnn3 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
Dim sql2 As String
Dim ds1 As New DataSet
Dim adptr As OleDbDataAdapter
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim Command1 As New OleDbCommand
Dim i2 As Integer
Dim sql1 As String
Dim Status As String
Try
Dim cnn3 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
cnn3.Open()
If ComboBox1.SelectedValue = "Admin" Then
Status = "Admin"
Else
Status = "Student"
End If
sql1 = "INSERT INTO Users ([ID],[PASSWORD],[LASTNAME],[FIRSTNAME],[LOGINTYPE]) VALUES('" & txtUID.Text & "','" & txtUPassword.Text & "','" & txtULastname.Text & "','" & txtUFirstName.Text & "','" & Status & "')"
Command1 = New OleDbCommand(sql1, cnn3)
i2 = Command1.ExecuteNonQuery
MessageBox.Show("Users Added Successfull")
Refresh()
Catch ex As Exception
End Try
End Sub
Private Sub btnback_Click(sender As Object, e As EventArgs) Handles btnback.Click
Me.Hide()
frmFaculty.Show()
End Sub
Private Sub frmUsers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Refresh()
End Sub
Private Sub Refresh()
Dim cnn4 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
sql2 = "Select * from Users"
Try
cnn4.Open()
adptr = New OleDbDataAdapter(sql2, cnn4)
adptr.Fill(ds1)
DataGridView1.DataSource = ds1.Tables(0)
Catch ex As Exception
End Try
cnn4.Close()
End Sub

How to take a backup of database of sql server 2005 in VB.net Using Code

I want to know how to take a backup of database using programatically in VB.net of SQL Server 2005. If you have an idea about it then please send me the code for that.
SQL Server Database Backup Utility using VB.NET and SQL-DMO (New version)
You can achieve this by using Sql Management Object. SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server.
Refer How to: Back Up Databases and Transaction Logs in Visual Basic .NET
Imports System.IO
Imports System.Data.SqlClient
Public Class Form2
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim dread As SqlDataReader
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
server(".")
server(".\sqlexpress")
End Sub
Sub server(ByVal str As String)
con = New SqlConnection("Data Source=" & str & ";Database=Master;integrated security=SSPI;")
con.Open()
cmd = New SqlCommand("select * from sysservers where srvproduct='SQL Server'", con)
dread = cmd.ExecuteReader
While dread.Read
ComboBox1.Items.Add(dread(2))
End While
dread.Close()
con.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If ComboBox1.Text = "" Then
MsgBox("select the server name")
ComboBox1.Focus()
Exit Sub
End If
Try
ComboBox2.Text = ""
con = New SqlConnection("Data Source=" & Trim(ComboBox1.Text) & ";Database=Master;integrated security=SSPI;")
con.Open()
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
ComboBox2.Text = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)
cmd = New SqlCommand("drop database " & ComboBox2.Text & " ", con)
cmd.ExecuteNonQuery()
cmd = New SqlCommand("RESTORE DATABASE " & ComboBox2.Text & " FROM disk='" & OpenFileDialog1.FileName & "'", con)
cmd.ExecuteNonQuery()
MsgBox("Restore Successfully Completed")
ComboBox1.Text = ""
ComboBox2.Text = ""
Else
MsgBox("Restore Cancelled")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ComboBox1.Text = "" Then
MsgBox("select the server name")
ComboBox1.Focus()
Exit Sub
ElseIf ComboBox2.Text = "" Then
MsgBox("select the database name")
ComboBox2.Focus()
Exit Sub
End If
Try
con = New SqlConnection("Data Source=" & Trim(ComboBox1.Text) & ";Database=Master;integrated security=SSPI;")
con.Open()
SaveFileDialog1.FileName = ComboBox2.Text + ".bak"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim s As String
s = SaveFileDialog1.FileName
cmd = New SqlCommand("backup database " & ComboBox2.Text & " to disk='" & s & "'", con)
cmd.ExecuteNonQuery()
MsgBox("Back Up Successfully Created")
ComboBox1.Text = ""
ComboBox2.Text = ""
con.Close()
Else
MsgBox("Back Up Cancelled")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
con = New SqlConnection("Data Source=" & Trim(ComboBox1.Text) & ";Database=Master;integrated security=SSPI;")
con.Open()
ComboBox2.Items.Clear()
cmd = New SqlCommand("select * from sysdatabases", con)
dread = cmd.ExecuteReader
While dread.Read
ComboBox2.Items.Add(dread(0))
End While
dread.Close()
con.Close()
End Sub
End Class