My code below does not block other user who's col1 and col2 in sql does not match. Need help resolve
trying to give access to user if userid matches dept name and open specific form. If userid1 and dept1 matches open Form1 and userid2 and dept2 matches open Form2 else unauthorized user.
Private Sub BTNLOGIN_Click(sender As System.Object, e As System.EventArgs) Handles BTNLOGIN.Click
Try
Dim myconn As New SqlClient.SqlConnection("connection string;")
myconn.Open()
Dim sql As String = "select USERNAME,DEPT FROM USERS where USERNAME = '" & TXTBUNAME.Text & "'AND DEPT='" & CmbDept.Text & "'"
Dim CMD As SqlCommand = New SqlCommand(sql, myconn)
Dim reader As SqlDataReader = CMD.ExecuteReader
If reader.Read Then
CmbDept.SelectedIndex = "#DEPT"
Me.Dispose()
Else
MessageBox.Show("Unauthorized User")
Me.Show()
End If
Catch ex As Exception
End Try
If CmbDept.Text.Trim = "option1" Then
Form1.Show()
End If
If CmbDept.Text.Trim = "option2" Then
Form2.Show()
End If
End Sub
my code is good for 1 user in each dept. How can I have multi users from same department but need to authenticate user id with environment login. No password isstored in SQL. Table col's USERID, EMP NAME & DEPT
Try
Dim conn As New SqlClient.SqlConnection("Connection String;")
conn.Open()
Dim Command As New SqlCommand("SELECT USERID,Dept FROM TABLENAME WHERE USERNAME ='" & UName & "'and Dept ='" & CmbDept.SelectedItem & "'", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(Command)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
If (CmbDept.SelectedIndex = 0) Then
Dim a As New form1
a.Show()
Me.Hide()
ElseIf (CmbDept.SelectedIndex = 1) Then
Dim b As New form2
b.Show()
Me.Hide()
End If
Else
MessageBox.Show("invalid User")
Me.Show()
End If
Catch ex As Exception
End Try
End Sub
On my login form, whenever clicking "btnLogin" it seems that "frmLogin" and also "frmMenu" decrease in width, and length. What is the reason for this? How can you fix it? I don't know if it's something to with the code or not, but I'll link it anyway. Thank you.
Imports System.Data.OleDb
Public Class frmLogin
Public AdminDetails As Boolean
Public SuccessfulLoginUsername As String
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = Application.StartupPath & "\SAC1 Database.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [tblUsers] WHERE [Username] = '" & txtUsername.Text & "' AND [Password] = '" & txtPassword.Text & "'", myConnection)
myConnection.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userFound As Boolean = False
Dim FirstName As String = ""
Dim LastName As String = ""
While dr.Read
userFound = True
FirstName = dr("FirstName").ToString
LastName = dr("LastName").ToString
End While
If userFound = True Then
If txtUsername.Text = "admin" And txtPassword.Text = "password" Then
AdminDetails = True
SuccessfulLoginUsername = txtUsername.Text
Else
AdminDetails = False
SuccessfulLoginUsername = txtUsername.Text
End If
frmMenu.Show()
frmMenu.lblTitle.Text = "Welcome " & FirstName & " " & LastName
frmMenu.lblGreeting.Text = "Howdy! " & FirstName & " " & LastName & ". What would you like to do today?"
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
End If
myConnection.Close()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End
End Sub
Private Sub linklblCreateAccount_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles linklblCreateAccount.LinkClicked
frmCreateAccount.Show()
End Sub
End Class
This may be an issue with DPI awareness. Specifically, your application is not declared as being DPI aware and when your code accesses the Microsoft.ACE.OLEDB provider, its process is set to being DPI aware. This is something that I discovered by accident a while ago, but I never seen anyone else report it happening.
The simple solution is to make your application DPI aware.
From the Project Menu, select "your project name"-Properties.
Select the Application Tab and click on the "View Window Settings" button.
Depending on your VS version, you may or may not have the following in the file.
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
-->
If you find this block, then remove the first and last lines ("< !--" and " -->"). If it is not present, add these lines right before the last tag in the file.
Rebuild your application.
I'm trying to refresh the DataGridView right after executing an SQL Command, so when the user presses the update button all details must change as well as the DataGridView. This is my code and I don't know where to add this function.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, Button5.Click
Try
Dim a As String
cn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd = New SqlCommand("update Addemployees set Fname= '" & TextBox1.Text & "', Lname= '" & TextBox3.Text & "', ID= '" & TextBox4.Text & "', CIN= '" & TextBox2.Text & "', phone= '" & TextBox6.Text & "', Email= '" & TextBox5.Text & "', fromD= '" & TextBox8.Text & "', toD= '" & TextBox7.Text & "' where ID='" & ComboBox1.Text & "' ", cn)
cmd.Connection = cn
a = cmd.ExecuteNonQuery()
MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
cn.Dispose()
End Try
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
DateTimePicker2 = Nothing
DateTimePicker1 = Nothing
End Sub
You can just create a Method or a Function that displays data in the DATAGRIDVIEW and then call the method whenever you add/delete/update just be sure to add/delete/update first before calling the method or function
Sub display()
Dim temp As Double = 0
Dim lt As String = "select id as ID, vlname as Last, vfname as First,
vmname as Middle, vgnd as Gender, vdob as Birthday, iage as
Age, vcourse as Course from tbreg where vlname Like '" +
tbsearch.Text + "%' or vfname Like '" + tbsearch.Text + "%'
order by vlname asc"
Dim da As New MySqlDataAdapter(lt, con)
con.Open()
Dim ds As New DataSet
da.Fill(ds, "tbreg")
da.Dispose()
dgv.DataSource = ds.Tables(0)
con.Close()
End Sub
Just add the display() method right after saving/deleting/updating your database
'updating and then refreshing the datagridview right after doing the update you
just have to call the method
Dim supdate As String = "Update tbuser set vname = '" & tbname.Text & "',
vemail = '" & tbemail.Text & "', vuser = '" &
tbuser.Text & "', vpass = '" & tbpass.Text & "' where
vid = '" & dgv.SelectedCells(0).Value & "'"
Dim cmd As New MySqlCommand(supdate, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!!!", MsgBoxStyle.Information,
"System COnfirmed!")
con.Close()
'display method here!
display()
You can do one thing here. After the save is successful, call the procedure you used to view the contents in DataGridView This works.
I will show you my example:
I have a student attendance adding/viewing form. There is a TabControl with two tabs, one for adding and another for viewing.
In the add tab, there is a button which submits the attendance of students to a database. After the submission is done, I then show a message like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
End Sub
In the view tab, there are few option on how the user wants to see the attendance record which is done by selecting option from ComboBoxes and then clicking the SearchBtn button.
'search attendance
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click
If SelectClass2.Text = "" Or SearchType.Text = "" Or SearchKey.Text = "" Then
MsgBox("Select search options to continue", MsgBoxStyle.Critical)
Else
If SearchType.Text = "By Date" Then
'search by date, call procedure 'displayatt'
Dim xyz As String = SearchKey.Text.Substring(0, 5)
displayatt(SearchKey.Text, SelectClass2.Text, String.Format("YYYY/MM/DD", xyz), True)
Else
'search by student, call procedure 'displayatt'
displayatt(SearchKey.Text.Substring(3, SearchType.Text.Length - 3), SelectClass2.Text, SearchKey.Text.Substring(0, 5), False)
End If
End If
End Sub
Well, you can update the DataGridView1 contents by calling the procedure which shows the contents. In my case, I would add SearchBtn_Click(SearchBtn, Nothing) right after showing the messagebox about the completion of adding the attendance. Then it will look like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
SearchBtn_Click(SearchBtn, Nothing)
End Sub
Try it. :)
Use this class for Microsoft SQL and see the LoadDB for how to use it. Also don't hardcode you query like you did. Someone using your app could do SQL injection and drop your tables. Use params like I showed you. You probably also want to update only a specific record so add the WHERE instruction in your query
Sub LoadDB
dim xdb as new dbMSSQL
dim SQLQuery as String = "update Addemployees set fname=#colfname, lname=#collanme, etc WEHRE ID=#colID"
xdb.addparam("#colid",RecordID)
xdb.addparam("#colfname",textbox1.text)
xdb.addparam("#collname",textbox2.text)
.......
xdb.execquery(Sqlquery)
datagridview1.datasource=xdb.dbdt
end sub
Imports System.Data.SqlClient
Public Class dbMSSQL
' CREATE YOUR DB CONNECTION
Public SQLSource As String = "Data Source=[yourcomputer]\sqlexpress;Integrated Security=True"
Private DBCon As New SqlConnection(SQLSource)
'Private DBCon As New MySqlConnection(SQLSource)
' PREPARE DB COMMAND
Private DBCmd As SqlCommand
' DB DATA
Public DBDA As SqlDataAdapter
Public DBDT As DataTable
' QUERY PARAMETERS
Public Params As New List(Of SqlParameter)
' QUERY STATISTICS
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
' RESET QUERY STATS
RecordCount = 0
Exception = ""
Try
' OPEN A CONNECTION
DBCon.Open()
' CREATE DB COMMAND
DBCmd = New SqlCommand(Query, DBCon)
' LOAD PARAMS INTO DB COMMAND
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' CLEAR PARAMS LIST
Params.Clear()
' EXECUTE COMMAND & FILL DATATABLE
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' CLOSE YOUR CONNECTION
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' INCLUDE QUERY & COMMAND PARAMETERS
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
here actual code from a project
Dim xDB As New mysql
xDB.AddParam("#colisconnected", 1)
xDB.AddParam("#colcpuid", CPUid)
xDB.AddParam("#colfwuid", userId)
xDB.ExecQuery("UPDATE clients.computerinfo SET isconnected=#colisconnected WHERE (cpuid=#colcpuid) and (customerid=#colfwuid)")
I am trying to create a forgot password screen for my application. I am using the tab control for the different pages. My current code is able to create a user but it is able to create duplicates (Which is an issue needed to be rectified) I then have an issue with the forget password screen not working completely.
My code is:
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Dim usernamevalid As Integer
Dim passwordvalid As Integer
Public Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If User.Text.Length < 4 Then
usernamevalid = 0
ElseIf User.Text.Length > 4 Then
usernamevalid = 1
End If
If Pass.Text.Length < 5 Then
passwordvalid = 0
ElseIf Pass.Text.Length > 5 Then
passwordvalid = 1
End If
If usernamevalid = 0 Then
MsgBox("Username Must Be At Least 5 Characters")
End If
If passwordvalid = 0 Then
MsgBox("Password Must Be At Least 5 Characters")
End If
If passwordvalid And usernamevalid = 1 And Pass.Text = RePass.Text Then
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Daniel\Documents\Robocopy.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = User.Text
DBTestP1 = Pass.Text
sql = "INSERT INTO Robocopy(username,[password],sq,sqa) VALUES('" & DBTest1 & "','" & DBTestP1 & "','" & SQREG.Text & "', '" & SQAREG.Text & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
MsgBox("User Created!")
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
ElseIf Not Pass.Text = RePass.Text Then
MsgBox("Passwords did not match")
End If
End Sub
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim result = MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel)
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If NewPass.Text = ReNewPass.Text Then
Try
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
End Class
The exception it catches is The ConnectionString property has not been initialized
Currently I changed my code to what I think you mean:
Button4's code has been changed as such:
Private Sub ResetPassword_Click(sender As Object, e As EventArgs) Handles ResetPassword.Click
If NewPass.Text = ReNewPass.Text Then
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
End Using
End Using
End If
End Sub
I now get the error for cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
I am getting the error for cmd where it says 'Read Only' Variable cannot be the target of assignment
The only thing I can see wrong with the connection string are extra spaces after 'Data Source='.
Here's an example from connectionstrings.com:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;
Here's my code, i am getting the error message "unknown table 'user' in field list"
How do i fix this?
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim mysqlconn As New MySqlConnection
Dim command As MySqlCommand
Dim query As String = ""
Dim reader As MySqlDataReader
Private Sub loginbutton_Click(sender As Object, e As EventArgs) Handles loginbutton.Click
getdbdata()
End Sub
Private Sub getdbdata()
Try
mysqlconn = New MySqlConnection("server=localhost;username=root;database=bank")
query = "select user.Username, user.Password, user.Email" & _
"from user"
command = New MySqlCommand(query, mysqlconn)
mysqlconn.Open()
reader = command.ExecuteReader
While reader.Read
txtusername.Text = txtusername.Text & reader.Item("Username") & vbCrLf
txtpassword.Text = txtpassword.Text & reader.Item("Password") & vbCrLf
txtemail.Text = txtemail.Text & reader.Item("Email")
End While
reader.Close()
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
Is the table "User" in the "Bank" database? If so try this:
query = "select Username, Password, Email " & _
"from [user]"