Backup of SQL Server database using VB.NET - vb.net

In vb.net, I'm trying to take a backup of my SQL Server 2012.
When I run my code it gets backup from database correctly (in the local), but when I change the connection to a server (local server), it doesn't do anything.
I think the problem is for the security on the server ...
Any solution regarding to solve this issue is greatly appreciated
My code :
Sub server(ByVal str As String)
con = New SqlConnection("Data Source=" & str & ";Initial Catalog=DATABASE;Persist Security Info=True;User ID=username;Password=password")
con.Open()
cmd = New SqlCommand("select * from sysservers where srvproduct='SQL Server'", con)
dread = cmd.ExecuteReader
While dread.Read
cmbserver.Items.Add(dread(2))
End While
dread.Close()
End Sub
Sub connection()
con = New SqlConnection("Data Source=192.168.0.200;Initial Catalog=database;Persist Security Info=True;User ID=username;Password=password")
con.Open()
cmbdatabase.Items.Clear()
cmd = New SqlCommand("select * from sysdatabases", con)
dread = cmd.ExecuteReader
While dread.Read
cmbdatabase.Items.Add(dread(0))
End While
dread.Close()
End Sub
Sub query(ByVal que As String)
On Error Resume Next
cmd = New SqlCommand(que, con)
cmd.ExecuteNonQuery()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
If PRGBackup.Value = 100 Then
Timer1.Enabled = False
PRGBackup.Visible = False
MsgBox("successfully the backup has been done in the specified folder.")
Else
PRGBackup.Value = PRGBackup.Value + 5
End If
Catch ex As Exception
MsgBox(ex.Message, , projectTitle)
End Try
End Sub
Sub blank(ByVal str As String)
Try
If cmbserver.Text = "" Or cmbdatabase.Text = "" Then
MsgBox("Server Name or Database can not be blank.")
Exit Sub
Else
If str = "backup" Then
SFDBackup.FileName = cmbdatabase.Text
SFDBackup.ShowDialog()
Timer1.Enabled = True
PRGBackup.Visible = True
Dim s As String
s = SFDBackup.FileName
Dim sql As String = "BACKUP DATABASE " & cmbdatabase.Text & " to disk='" & s & "'"
query(sql)
ElseIf str = "restore" Then
OFDBackup.ShowDialog()
Timer1.Enabled = True
PRGBackup.Visible = True
query("RESTORE DATABASE " & cmbdatabase.Text & " FROM disk='" & OFDBackup.FileName & "'")
End If
End If
Catch ex As Exception
MsgBox(ex.Message, , projectTitle)
End Try
End Sub
Private Sub cmbbackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbbackup.Click
blank("backup")
End Sub
Private Sub cmdrestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdrestore.Click
blank("restore")
End Sub
Private Sub frmBackup_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.Cursor = Cursors.WaitCursor
server("192.168.0.200")
'server(".\sqlexpress")
Me.Cursor = Cursors.Default
Catch ex As Exception
MsgBox(ex.Message, , projectTitle)
End Try
End Sub

You need to execute a backup SQL command:
Dim sqlConnectionString As String = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Locations;Data Source=GIGABYTE-PC\SQLEXPRESS"
Dim conn As New SqlConnection(sqlConnectionString)
conn.Open()
Dim cmd As New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "BACKUP DATABASE Locations TO DISK='C:\Temp\location.BAK'"
cmd.Connection = conn
cmd.ExecuteNonQuery()

I think you just missed the SQL server instance name, which is after the IP Address backslash sign directly "\": ========> "172.16.9.26\SQLSERVER;"
try this connection since you are using the IP address and you also have a user name and password:
Dim ConnString As String = ("Server=172.16.9.26\SQLSERVER;Database=database;User Id=sa;Password=yourpass")
So, make your SqlConnection like this:
con = New SqlConnection("Data Source=192.168.0.200\SQLSERVER;Initial Catalog=database;Persist Security Info=True;User ID=username;Password=password")
I hope this can help.
^_^

It will take the backup but the backup file will goes to some directory on the server and not on the local client

If your local computer name is duo-1 and backup file path is D:\Apps\Medlabs i9\DATA BACKUP\Medlabs.bak then
then you should use UNC path in backup query.It should be
backup database DB_NAME to disk='\\duo-1\D\Apps\Medlabs i9\DATA BACKUP\Medlabs.bak'

Related

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

“syntax error in INSERT INTO statement”

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?
Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.
You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

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 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

login form using ms access in 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