I have created two form for Login module. One for the admins and one for the customers.
Admin:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbAdmin where admin_id=' " + txtUsername.Text + " ' and admin_password='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
Customer:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbLogin where username=' " + txtUsername.Text + " ' and pass='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
They are basically just the same, except that both of them are in different form and are based on different tables. But for some reason, the Customer log in is not working, even though the inputs are correct and matches the records in database, it always shows it's invalid.
In database, tbAdmin's primary key is admin_id and tbCustomer's primary key is username.
Is it possible that it's kind of interrupting the connection because they basically all have the same variable name? But they're in different form and admin log in is perfectly fine.
I would like to apologize, I am new to connecting vb.net to sql.
one thing I notice is you leave a space between the colon
Try this
"select * from tbLogin where username='" & txtUsername.Text & "' and pass='" & txtPassword.Text & "'"
Also if you do not want it to be case sensitive you always use 'like'
"select * from tbLogin where username like '" & txtUsername.Text & "' and pass like '" & txtPassword.Text & "'"
Related
How can I make a refresh button for mine DB which withdraws to DataGrid? I have this:
Dim con As New MySqlConnection()
con.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" + "password= " + password + ";" + "database =" + database
con.Open()
'Dim query As String
'query = "select * from suspects_arrests"
Dim cmd As New MySqlCommand()
cmd.CommandText = "select * from suspects_arrests"
cmd.Connection = con
Dim sqlAdap As New MySqlDataAdapter(cmd)
Dim dt As New DataTable("suspects_arrests")
sqlAdap.Fill(sqlData)
DataSuspects.ItemsSource = sqlData.DefaultView
con.Close()
But this is duplicating records. DataSuspects.Items.Refresh/Clear not working. On Items.Clear() goes this error:
The operation is invalid when the ItemsSource is in use. Instead, access and modify items using ItemsControl.ItemsSource
Not pressed (screenshot)
When pressed
This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data
I am relatively new to programming in VB.
Currently, I have a login page that works fine. After successful login, my user is directed to another form which connects back into an MS Access table and presents data on the screen for them.
I take the logged in user and equal it to a label on the secondary form (after they login). Basically I want to have a SQL select statement for if the Username column in my access db equals that label, then to pull back the data for that unique user. Here is my current code:
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = '" + Label1.Text + "'""
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.Fill(ds, "studentclasslist")
con.Close()
It doesn't work. When I take the where statement out and just do "Select * From Table1" it works fine, but doesn't give me a unique logged in user, which is my goal.
Please help!
You should store your login user id in the session when user logged in successfully.
//In your login page
Session["myUser"] = txtUsername.Text
Then, you can use the user id from Session anywhere in your application.
//In your other page.
Dim Cmd As OleDbCommand = connection.CreateCommand()
Cmd.CommandText = "SELECT * FROM Table1 WHERE Username=?"
Cmd.Parameters.Add("#Username",OleDbType.Text,50).Value = Session["myUser"]
Dim da As New OleDbDataAdapter(Cmd)
Dim dt As New DataTable()
da.Fill(dt)
It din't work because of, misused double quotation.
May be Something like this
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = '" & Label1.Text & "'"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.Fill(ds, "studentclasslist")
con.Close()
But this will leads you to SQL injection attacks. use parameterized queries to treat input as values in your SQL queries.
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
con.Close()
To prevent from SQL injection as parameters as already been widely suggested. Additionally, you could use Using for you connection to dispose right away the connection after it is being used like:
Using con As New OleDbConnection(DbProvider & DbSource)
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
End Using
Secondly, you can put the data on a DataTable
Dim dt as new DataTable
dt = ds.Tables(0)
And assuming that you have one record match you could check if there are records by checking Records.Count and if there is save it to a DataRow and then Textboxes.
If (dt.Rows.Count > 0) Then
Dim dr as DataRow = dt.Rows(0)
'Field names and Textbox names below are just mine
txtUserName.Text = dr.Item("Username")
txtPassword.Text = dr.Item("Password")
txtUserlevel.Text = dr.Item("UserLevel")
End If
So, all in all it would probably look like this:
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
Using con As New OleDbConnection(DbProvider & DbSource)
Dim dt as new DataTable
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
dt = ds.Tables(0)
If (dt.Rows.Count > 0) Then
Dim dr as DataRow = dt.Rows(0)
'Field names and Textbox names below are just mine
txtUserName.Text = dr.Item("Username")
txtPassword.Text = dr.Item("Password")
txtUserlevel.Text = dr.Item("UserLevel")
End If
End Using
thanks everyone. it was the double quote. works now but next is making it sql injection proof which i will learn how to use parameterized queries to prevent against.
In a Login form for VB.Net connected to an Oracle database.. Is there a way of inserting an If statement to direct different users to different forms.. Eg, an accountant to the accounting home page or a driver to a driver homepage even though all there ID's and passwords are in the one table within the database.
There is a POSITION field within the database and this is what I would like to use to differentiate the different users levels of access.
Here is the code working so far:
Dim conn As New OleDb.OleDbConnection
conn.ConnectionString = _
"Provider=msdaora;Data Source=orabis;User Id=112221800;Password=112221800;"
conn.Open()
Dim parmuser As New OleDb.OleDbParameter
parmuser.OleDbType = OleDb.OleDbType.Char
parmuser.Value = txtStaffNo.Text
Dim parmpass As New OleDb.OleDbParameter
parmpass.OleDbType = OleDb.OleDbType.Char
parmpass.Value = txtPassword.Text
Dim cmd As New OleDbCommand
cmd.Connection = conn
cmd = New OleDbCommand("select STAFFID,PASSWORD from STAFF where STAFFID ='" & txtStaffNo.Text & "' and PASSWORD ='" & txtPassword.Text & "'", conn)
cmd.CommandType = CommandType.Text
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader()
If txtStaffNo.Text = "" Or txtPassword.Text = "" Then
MessageBox.Show("You have not entered any values!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf dr.Read() Then
txtStaffNo.Text = dr("STAFFID")
txtPassword.Text = dr("PASSWORD")
MsgBox("Access Allowed")
CustOption.Show()
Me.Hide()
Else
'MessageBox.Show("Wrong Username and Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'intCount = intCount + 1
End If
In your SELECT statement, add position there so it would be:
cmd = New OleDbCommand("select POSITION, STAFFID,PASSWORD from STAFF where STAFFID ='" & txtStaffNo.Text & "' and PASSWORD ='" & txtPassword.Text & "'", conn)
Then after you validate the user, you just use a select case like:
Dim empPosition as string = dr("POSITION") ' assuming it's a string here
select case empPosition.toLower
case "driver"
' open driver form
case "accountant"
'open accountant form
' more case statements for other positions.
End Select
Here is my code:
Dim sqledit As New SqlCommand
sqledit = New SqlCommand("UPDATE Branches SET StAddress='" + txtstaddress.Text + "',City='" + txtcity.Text + "',Province='" + txtprovince.Text + "',ContactNo='" + txtcontact.Text + "' WHERE BranchID='" + txtbranchid.Text + "'", con1)
sqledit.ExecuteNonQuery()
MsgBox("Branch Information Updated!", MsgBoxStyle.Information, Title:="Edit Branch Information")
utilities.Refresh()
Me.Close()
I can't get to update it even if I refresh it. Please help!
There is easy way too
you can make a query by your datagridview that call all of your table content
example:
SELECT {your table field}
FROM {table name}
If you execute this query after changes it will show you the new data on DGV.
The best way to achieve this is reload the data grid view. Here is the code that explains how to do it
Private Sub refreshDatagrid()
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=reerp;User ID=root;Password=root;")
Dim sql As MySqlCommand = New MySqlCommand("SELECT * FROM users", con)
Dim ds As DataSet = New DataSet()
Dim DataAdapter1 As MySqlDataAdapter = New MySqlDataAdapter()
con.Open()
DataAdapter1.SelectCommand = sql
DataAdapter1.Fill(ds, "Users")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Users"
con.Close()
End Sub
now once you have added data to your grid then just call this method again. here is and example of how you do it
Dim query As String
Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=reerp;user id=root;password=root;")
query = "insert into users (username,password,first_name,last_name,role) values('"
query = query + tb_username.Text + "','" + tb_password.Text + "','" + tb_firstname.Text + "','" + tb_lastname.Text + "','" + ComboBox_role.Text + "');"
con.Open()
Dim cmd As MySqlCommand = New MySqlCommand(query, con)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
lblMsg.Text = "record is successfully inserted"
refreshDatagrid()
Else
lblMsg.Text = "record is not inserted"
End If
con.Close()