|
-
Jun 26th, 2019, 08:38 AM
#1
Thread Starter
Junior Member
Transfer login info to label/textbox
Hey again, another problem, same project.
Well, I'm working on a project where I want a login, register, and a profile form. I've accomplished to make login and register work perfectly, but I have no clue on how to make the profile. I want to make a profile form where I show the info of the user, that he introduced in the registration process (Username, Profile Nome) as well as some information like country and birthday that I want them to fill later on, inserted in text boxes or even labels. I will let the login and registration code below so you guys can understand the methods I used. Thx in advance!
Login Code:
Code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim uname As String = ""
Dim pword As String
Dim username As String = ""
Dim pass As String
If txtUser.Text = "" Or txtPassword.Text = "" Then
MsgBox(erro1)
Else
uname = txtUser.Text
pword = txtPassword.Text
Dim querry As String = "Select PalavraPasse From tblusers where Username= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(querry, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MessageBox.Show("O Username não existe", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
txtUser.Text = ""
txtPassword.Text = ""
End Try
If (pword = pass) Then
MessageBox.Show("Login realizado com sucesso!", "Login Info", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
'Substituir Message box por um personalizado com timer
FormHome.Show()
If FormHome.Visible Then
Me.Hide()
Else
MessageBox.Show("O login falhou!", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
txtUser.Text = ""
txtPassword.Text = ""
End If
End If
End If
End Sub
Register Code:
Code:
If txtPassw.Text = txtConfirmarPassw.Text Then
If txtUsername.Text = "" Or txtNomePerfil.Text = "" Or txtPassw.Text = "" Then
MsgBox(erro1)
Else
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb")
Dim insert As String = "Insert into tblUsers(Username , NomePerfil , PalavraPasse) values('" & txtUsername.Text & "','" & txtNomePerfil.Text & "','" & txtPassw.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Conta criada com sucesso!")
Me.Close()
FormLogin.Visible = True
Catch ex As Exception
MsgBox(erro2)
End Try
End If
Else
MsgBox(erro2)
txtPassw.Text = ""
txtConfirmarPassw.Text = ""
End If
Disclaimer: I have made a question in the forum earlier where I was clear that I'm using an Access database, and many people answered me saying that my SQL code was wrong, so I want to make sure that it is clear that I'm using MS Acess. Ty
Edit: You might not understand some msgbox messages because they are in Portuguese, any doubt pls comment bellow
Last edited by Danii; Jun 26th, 2019 at 08:39 AM.
Reason: Clarifications
-
Jun 26th, 2019, 09:06 AM
#2
Re: Transfer login info to label/textbox
Somebody probably already mentioned that you should be using parameters rather than concatenating user supplied text directly into a query. The way you are doing it leaves the code open to SQL injection attacks.
I was also going to say that there is a more efficient way to get the password back, but considering your actual question, it might be best to use a less efficient means to get the password back. After all, it looks like the record that contains the password also contains the other fields that you want to display. You are currently using ExecuteScalar to get the password back and check it. ExecuteScalar is the fastest means, but it only returns one field. In this case, you would like the password, but you'd like a few other fields, as well, so you could use a DataReader returned by ExecuteReader rather than ExecuteScalar. You would then check that the password is correct, as you are doing, and if it is, then the reader would also have the other fields, so you could put them where you want them.
There is a potential security hole with that approach, but the security hole exists just as much for the code the way you currently have it, so you wouldn't be making it worse.
A better solution would be to change the login portion pretty thoroughly:
Code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If txtUser.Text = "" Or txtPassword.Text = "" Then
MsgBox(erro1)
Else
Dim querry As String = "Select Username , NomePerfil From tblusers where Username= ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using cmd As conn.CreateCommand
conn.Open()
cmd.Parameters.AddWithValue("@p1",txtUser.Text)
cmd.Parameters.AddWithValue("@p2",txtPassword.Text)
Try
Using dr As DataReader = cmd.ExecuteReader()
If dr.Read()
'You got a match on the username and password, and you now have the data you want.
Else
'No name and password matched.
End If
End Using
Catch ex As Exception
'This message is now a bit misleading.
MessageBox.Show("O Username não existe", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
txtUser.Text = ""
txtPassword.Text = ""
End Try
End Using
End Using
End If
End Sub
This fixes up a few things. For one thing, the Using blocks will properly clean up the Command, DataReader, and Connection objects, even if an exception is thrown. This includes closing the connection.
The problem with the way you had it is that the code could keep running for different user names, and would keep returning the passwords. They might not match, but they'd be returned. That seems like a means that could be used to figure out the passwords, though if that was done, you'd likely have much worse problems than just this, so as a flaw it's pretty minor. Still, with this approach, you can pass in the username and password, and you ONLY get something back if there is a record that matches that particular combination of username and password. Technically, this also means that you can have multiple users with the same username as long as they have different passwords, though that's still a bad idea.
One better thing about this is that you can store hashed passwords rather than storing the actual password in the database. Rather than passing in what the user entered, you'd hash whatever the user entered, and pass the hashed value. If the hashed value matched, then the user entered the right password. If the hashed value didn't match, then the user passed in the incorrect password. However, if somebody stole your database they wouldn't have the actual passwords, they'd just have the hashed passwords, which would be nearly useless to them if you hashed them correctly.
Using parameters avoids SQL injection attacks, but I may have written the parameters incorrectly for Access. Access doesn't allow named parameters. It just inserts parameters in place of the ? marks in the order the parameters are supplied. I put names on the parameters (@p1), which would work in a DBMS that used named parameters. I believe they do no harm and no good when it comes to Access. I may be wrong about that, so those names may be an issue.
As to the reader, when you call Read, it reads the next row and returns True if there is one and False if there is not. So, if there was no record that matched the username and password, Read would return False. If there IS a record that matched the username and password, Read would return True, and you can access the fields returned like so:
Either dr(0).ToString or dr("Username").ToString would be the username.
Either dr(1).ToString or dr("NomePerfil ").ToString would be the NomePerfil, whatever that is.
So, if dr.Read returns True, you have the data, so put it into whatever label you want it in.
My usual boring signature: Nothing
 
-
Jun 26th, 2019, 10:49 AM
#3
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Hey, ty, I really appreciate how fast you are giving some answer!
Well, I'm getting 2 errors when fully substitute my login code from yours saying some things are not defined..
I'm getting errors in the following lines :
Code:
Using cmd As conn.CreateCommand
Code:
Using dr As DataReader = cmd.ExecuteReader()
I really hope you can help me.
Just one more thing, if it is not asking too much, can you pls check if I can improve my register method? And some lines in how to transform the data into text? its just lblUsername.text = dr("Username").ToString in the FormProfile.Load?
Ty
-
Jun 26th, 2019, 11:12 AM
#4
Re: Transfer login info to label/textbox
Yep, wrote that freehand and made a mistake. This is wrong:
Code:
Using cmd As conn.CreateCommand
It should have been
Code:
Using Cmd as OleDBCommand = conn.CreateCommand
The second line is due to a mistake in the name. I believe that the DataReader used for Access is actually OleDBDataReader, so the line should be:
Code:
Using dr As OleDBDataReader = cmd.ExecuteReader()
My usual boring signature: Nothing
 
-
Jun 26th, 2019, 11:15 AM
#5
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
I'm getting me the error "Username doesn't exist"
-
Jun 26th, 2019, 12:56 PM
#6
Re: Transfer login info to label/textbox
Really? If you're getting that when you try the query, then that's from your code, not mine. What should the column name be? I just copied the SQL that you had already written and said was working. It seems like there is a space missing, but it was missing in your code, too, so I guess the parser is smart enough to figure that out. You wouldn't get that particular error due to the space, anyways.
If you aren't getting the error from the query, where are you getting it?
My usual boring signature: Nothing
 
-
Jun 26th, 2019, 02:00 PM
#7
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
the only thing i did was copy your code into my btnLogin, and made the changes you said in #4, nothing else
to clarify: thats the messagebox i inserted, not acctualy visual studio telling me that, is one of the errors that i coded to figure out why something isn't working.
-
Jun 26th, 2019, 02:19 PM
#8
Re: Transfer login info to label/textbox
If you want your problem solved then you need to provide all the necessary information. Always post the relevant code, if there's an error, which line of code is causing the error. We have no idea what your code looks like now.
-
Jun 26th, 2019, 02:53 PM
#9
Re: Transfer login info to label/textbox
Yeah, I'd have to agree. After all, what I posted wasn't complete, as I didn't do anything based on whether or not the datareader found anything. You also say that you inserted a messagebox, so you certainly changed the code in at least that amount. Therefore, I don't know what the code looks like now.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 04:18 AM
#10
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Well, I will paste here the code needed to see if you guys can help me here and I will try to translate everything that isn't in English.
To help clarify, in my MS Access database I have the following fields and what they save:
tblusers - Name of the table
ID - Id of the account
Username - Saves the name people will use to login
NomePerfil (translated: ProfileName) - Saves the name that will be displayed in profile and etc, this one can be repeated
PalavraPasse (translated: Password) - Saves the password of the username
FormLogin:
Code:
Imports System.Data.OleDb
Imports System.Data
Public Class FormLogin
Dim mouse_move As System.Drawing.Point
Dim erro1 = "Por favor, preencha todos os campos" '-> "please fill all the fields"
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If txtUser.Text = "" Or txtPassword.Text = "" Then
MsgBox(erro1)
Else
Dim querry As String = "Select Username , PalavraPasse From tblusers where Username= ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
conn.Open()
Cmd.Parameters.AddWithValue("@p1", txtUser.Text)
Cmd.Parameters.AddWithValue("@p2", txtPassword.Text)
Try
Using dr As OleDbDataReader = Cmd.ExecuteReader()
If dr.Read() Then
MessageBox.Show("Login realizado com sucesso!", "Login Info", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) '->"login sucessfull"
Else
MessageBox.Show("O login falhou!", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) '-> "login failed"
End If
End Using
Catch ex As Exception
'This message is now a bit misleading. '-> didnt understood if you said this cause you didnt understood because it is in portuguese
MessageBox.Show("O Username não existe", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) '-> "username does not exist" (im getting this error)
txtUser.Text = ""
txtPassword.Text = ""
End Try
End Using
End Using
End If
End Sub
Private Sub chkMostrarPass_CheckedChanged(sender As Object, e As EventArgs) Handles chkMostrarPass.CheckedChanged
If chkMostrarPass.CheckState = CheckState.Checked Then
txtPassword.UseSystemPasswordChar = False
Else
txtPassword.UseSystemPasswordChar = True
End If
End Sub
Private Sub LinkConvidado_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkConvidado.LinkClicked
txtUser.Text = "Convidado"
txtPassword.Text = "Convidado" ' "Convidado" means "guest", this was the most easy way to create a guest so people are not forced to log in
btnLogin.PerformClick()
End Sub
End Class
Well, I guess there is all the info that is relevant, ty for your patience and your time.
-
Jun 27th, 2019, 09:03 AM
#11
Re: Transfer login info to label/textbox
And with that you get an exception saying Username doesn't exist? That's a bit of a surprise. There are a couple items in the query that might be slightly off, though SQL usually works those out. Try out this SQL:
"Select Username, PalavraPasse From tblusers where Username = ? And PalavraPasse = ?"
I only made two, very slight, changes. I'm wondering whether the trailing space in Username , was causing an issue? So, if that solves it, that was likely the issue. If that doesn't solve it, then the only place I see Username anywhere in the code is in that line, so, unless I'm overlooking some other place where it exists, then check the DB to make sure that the spelling is correct.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 09:08 AM
#12
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Changed what you just said, nothing has changed
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 09:26 AM
#13
Re: Transfer login info to label/textbox
Are you sure the spelling is correct?
By the way, I assume that when you say the error is happening, that you mean that an exception is thrown, and is being caught in the exception handler shown in your code. If that's not the case, then please clarify.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 09:40 AM
#14
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Every time I try to log in, using Usernames and Passwords from my database or using just some random characters, i will get always this line;
Code:
Catch ex As Exception
'This message is now a bit misleading. '-> didnt understood if you said this cause you didnt understood because it is in portuguese
MessageBox.Show("O Username não existe", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) '-> "username does not exist" (im getting this error)
txtUser.Text = ""
txtPassword.Text = ""
Only if i dont intruduce nothing in either txtUser or txtPassword i will get the message box from the variable erro1:
Code:
If txtUser.Text = "" Or txtPassword.Text = "" Then
MsgBox(erro1)
Else
While I was waiting for your response, I was checking the spelling and couldn't find anything wrong, I'm not a very good programmer, but I think, from what I understood, that is everything correct.
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 10:09 AM
#15
Re: Transfer login info to label/textbox
When you get the exception, that Ex has two parts. There's an exception type, which is fairly generic, such as "Invalid Operation Exception", or something like that. There is also a message that often has more information. I was thinking that what you posted in #5 was the message from the exception, but now that I look at it, isn't what you posted in #5 just the English translation of your textbox?
The reason I said the textbox is no longer accurate is because an exception doesn't mean that the username doesn't exist. An exception now means something totally different, and you need to know what it is. So, what you are showing in the textbox isn't going to do. Instead, show Ex.Message. That's the important information, as it will be an important clue as to what is wrong.
I have often found that when I thought I knew what was causing an exception, I was wrong. By showing Ex.Message, you will know much more about what is wrong.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 10:41 AM
#16
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
I did what you said, I will try to translate to English the error:
" the command text wasn't defined to the Command object"
I guess that's how the translation should be.
Well, I've realized now, my VB 2012 is in English, but the ex.Message is in Portuguese, I don't understand why.
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 11:20 AM
#17
Re: Transfer login info to label/textbox
Code:
Dim querry As String = "Select Username , PalavraPasse From tblusers where Username= ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
conn.Open()
Cmd.Parameters.AddWithValue("@p1", txtUser.Text)
Cmd.Parameters.AddWithValue("@p2", txtPassword.Text)
Try
you created the query, but never set it to the command object... so it had no idea what query you want to execute.
Code:
Dim querry As String = "Select Username , PalavraPasse From tblusers where Username= ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
cmd.CommandText = query ' ----- I think this is what you're missing.
conn.Open()
Cmd.Parameters.AddWithValue("@p1", txtUser.Text)
Cmd.Parameters.AddWithValue("@p2", txtPassword.Text)
Try
I think I have that line right... I don't have a way to test it and I don't have VS infront of me to double check... but it should at least get you in the right direction.
-tg
-
Jun 27th, 2019, 11:27 AM
#18
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
 Originally Posted by techgnome
[code]
I think I have that line right... I don't have a way to test it and I don't have VS infront of me to double check... but it should at least get you in the right direction.
-tg
Ty for helping me, I'm not getting the ex.Message now.. buuuuut, im getting the msgbox in this line:
Code:
Else
MessageBox.Show("O login falhou!", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) '-> "login failed"
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 11:28 AM
#19
Re: Transfer login info to label/textbox
Yep, that was it. My mistake.
I had misunderstood post #5. I thought that was the error message, which sent me looking at the text of the SQL statement. Now that I see the actual error message, I realize I had left out that step. That's what happens when you type it freehand like that.
By the way, you avoided that error originally because of the way you created the Command object. You passed the SQL string to the constructor, which takes care of the problem in one step. I prefer the nested Using statements, and creating the Command object from the Connection, which gives the Command object the Connection object, but not the SQL string. There isn't a right or wrong to this, it's just a matter of preference. Of course, you do have to not skip a step, as I did, but that's not the step I usually skip. The one I usually skip is opening the connection.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 11:35 AM
#20
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
 Originally Posted by Shaggy Hiker
Yep, that was it. My mistake.
I had misunderstood post #5. I thought that was the error message, which sent me looking at the text of the SQL statement. Now that I see the actual error message, I realize I had left out that step. That's what happens when you type it freehand like that.
By the way, you avoided that error originally because of the way you created the Command object. You passed the SQL string to the constructor, which takes care of the problem in one step. I prefer the nested Using statements, and creating the Command object from the Connection, which gives the Command object the Connection object, but not the SQL string. There isn't a right or wrong to this, it's just a matter of preference. Of course, you do have to not skip a step, as I did, but that's not the step I usually skip. The one I usually skip is opening the connection.
Ty for explaining what happened, that way I can understand better these connections in a future project, a big ty.
But I still have the problem I said below, that is going to this error :
Code:
Else
MessageBox.Show("O login falhou!", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) '-> "login failed"
And I still don't know how to Transfer login info to label/textbox
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 11:37 AM
#21
Re: Transfer login info to label/textbox
Posted as you were replying.
So, now the code is working without error...but isn't finding a match for what was passed in. That can be a particularly tricky problem to solve. I assume that you are supplying a valid username and password, but the database is saying that there is no record with that combination of username and password. So why not? It could be simple, or not, so you'll have to explore it a bit.
With the current code, the first thing I would do would be to change the SQL string to this:
"Select Username , PalavraPasse From tblusers where Username= ?" ' And PalavraPasse = ?"
In other words, chop the password part off the SQL, temporarily. Also comment out the line that adds the password parameter. Does it work like that? If not, then the problem is with the username. If it does work, then undo those changes, comment out the username parameter, and remove the Username portion from the SQL, and try again. Basically, this would be trying each piece to narrow down whether it is the username or the password.
It might not be either one, so it might not work either way. Access is a bit weird with parameters, and I rarely work with it. I think I got them right, and TG didn't correct me, but perhaps I didn't. So, the next step would be to change the SQL to this:
"Select Username , PalavraPasse From tblusers where Username= '" & txtUser.Text & "' And PalavraPasse = '" & txtPassword.Text & "'"
Ultimately, that's a bad thing to do, because people with malicious intent can wreck your database if you do that, but as a test it is a good one. You'd also want to comment out both parameters, since this wouldn't be using them for the test. If this works, then I got something wrong with the parameters. If it doesn't work, and you don't get any exceptions, then either the username or password is wrong, even though you think it is right. That's where things would get interesting.
My usual boring signature: Nothing
 
-
Jun 27th, 2019, 11:49 AM
#22
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Commenting all the password-related code, it says that the login was successful, so, the problem is getting the password?
Same boring questions as ever, ty for wasting your time with me!
-
Jun 27th, 2019, 12:08 PM
#23
Re: Transfer login info to label/textbox
Yeah, sure sounds like it. One further test would be to change the SQL to this:
"Select Username , PalavraPasse From tblusers where Username= ? And PalavraPasse = '" & txtPassword.Text & "'"
and comment out the password parameter. This does two things. For one thing, if this fails, you can feel pretty certain that the parameter isn't doing anything. Better yet, you can take a look at it.
I'm not sure if you have worked with breakpoints, yet. Classes often skip over that subject, which is terrible, in my opinion, because there is no more powerful tool at your disposal. Using Messageboxes is a really poor substitute, though occasionally useful. To set a breakpoint, put the cursor in the line where you want to set the breakpoint and press F9. This will add a maroon ball in the left margin. From then on, you never need to use F9 again, as you can always just click where the maroon ball is to set a breakpoint, and click on the ball to remove a breakpoint. They are so very useful that they are one of the easiest things to add and remove.
With a breakpoint, execution will stop when it gets to that line. At that point, you can look at what any variable holds. Usually you can do this by hovering the mouse over the variable, but sometimes you need to select it and press Shift+F9. You can also step forwards through the code using F10 or F11 (they do different things), and go back to running as normal using F5. This allows you to see what the program is doing, how variables change with each line, which paths are taken at branches, and so forth. Without breakpoints you are guessing, with breakpoints you can watch every step of the way.
So, in this case, I'd put a breakpoint on some line like this one:
conn.Open()
When execution stops, you can look at what is in querry. It will have the password in place, though the username will just show the ?. It should look about like you'd expect it to look. Seeing the command text with the parameters inserted is harder to do, and not usually all that useful.
There has to be some difference between the password in the database record and the password you are entering, so you are just trying to see any possible difference.
Also, once it works, to show the data being returned, assuming you had a label you would just add something like this:
yourLabel.Text = dr(0).ToString
Having looked back over the conversation, I would assume that what you'd actually want to return is NomePerfil. After all, you already have Username and PalavraPasse, so there is little reason to return them from the database.
My usual boring signature: Nothing
 
-
Jun 28th, 2019, 09:56 AM
#24
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
 Originally Posted by Shaggy Hiker
yourLabel.Text = dr(0).ToString
Heey, ty for all of your support, but again, I'm facing another problem...
I'm using that line you wrote for retrieving the data in a label (I'm wanting to retrieve the data in a textbox but I'm sure I just need to change the text for txtUsername.Text = something), but it doesn't work.
I'm assuming it's because I didn't make my self clear enough. If I'm not mistaken, that code its to use in the btnLogin where all the login code takes place, but I want to retrieve the data in another form. To make things more easily understandable the program should work like this:
-Create an account in FormRegister
-Login in the FormLogin
-Once the login is successful, head the user to FormHome
-In FormHome a button will appear, from pressing that button a FormProfile will open
-Inside FormProfile will be some textboxes displaying information about the account that logged in (txtUsername, txtNomePerfil, etc)
Is in FormProfile that I want to display all the info. I tried this, cause I don't know what more I can do, failed miserably...
Code:
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
Using dr As OleDbDataReader = Cmd.ExecuteReader()
txtNomePerfil.Text = dr(0).ToString
End Using
End Using
End Using
Same boring questions as ever, ty for wasting your time with me!
-
Jun 28th, 2019, 01:00 PM
#25
Re: Transfer login info to label/textbox
No, that's pretty close. I assume you got some error about there being no current record, or something like that, though maybe it was a bit different. You left out a couple steps. For one thing, I don't see any SQL statement. I would assume that you'd use the same SQL statement as you had on the other form, but you certainly do need one.
Second, when you create the reader, you have to call Read on it for it to get the first row. Doing this at the click of a button on a second form is fine, but the code is essentially the same as the code from the first form. You'd pass the username and password to the second form, then use that in the SQL statement. Alternatively, you could just leave the login code, get the data from the datareader there, put it in a couple variable, pass those variables to the second form, and when the user clicks the button, just put the data from the variables into the form.
My usual boring signature: Nothing
 
-
Jun 28th, 2019, 01:33 PM
#26
Re: Transfer login info to label/textbox
You posted the code, so that's good but what you haven't done is tell us where that code is located. Is it in the Form Load event? A Button Click event?
Also, keep in mind that a DataReader, like the name implies is only for reading data. If you're going to allow the user to modify any data then you probably should use a DataAdapter.
-
Jul 2nd, 2019, 05:44 AM
#27
Thread Starter
Junior Member
Re: Transfer login info to label/textbox
Hi guys, ty for your help and excuse me for the time I've taken to respond,
Well, I will paste here the code I'm trying to use to get the login information into a readOnly label:
Code:
Imports System.Data.OleDb
Imports System.Data
Public Class FormPerfil
Private Sub FormPerfil_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
Using dr As OleDbDataReader = Cmd.ExecuteReader()
txtNomePerfil.Text = dr(0).ToString
End Using
End Using
End Using
End Sub
End Class
I know that probably this is really terrible, but I couldn't put DataReader to work. To make things really clear, I have some textboxes "txtUsername" and "txtNomePerfil" (in English would be a txtProfileName) in FormLogin where I want to display the information of the logged person, that the user provides in the login.
Later on, I would like to insert a "txtNacionality" and a "txtBirthDate" that the user can write/choose from a list later if you could tell me that afterward, it would be amazing.
Reminder, the Login code that Shaggy said me to use instead of mine is being used, in case of doubt, I will paste it below:
Code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If txtUser.Text = "" Or txtPassword.Text = "" Then
MsgBox(erro1)
Else
Dim querry As String = "Select Username, PalavraPasse From tblUsers where Username = ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
conn.Open()
Cmd.CommandText = querry
Cmd.Parameters.AddWithValue("@p1", txtUser.Text)
Cmd.Parameters.AddWithValue("@p2", txtPassword.Text)
Try
Using dr As OleDbDataReader = Cmd.ExecuteReader()
If dr.Read() Then
MessageBox.Show("Login realizado com sucesso!", "Login Info", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) "Login sucessful"
FormHome.Show()
Me.Hide()
Else
MessageBox.Show("O Username não existe!", "Login Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) "Username does not exist"
txtUser.Text = ""
txtPassword.Text = ""
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
txtUser.Text = ""
txtPassword.Text = ""
End Try
End Using
End Using
End If
Same boring questions as ever, ty for wasting your time with me!
-
Jul 2nd, 2019, 09:30 AM
#28
Re: Transfer login info to label/textbox
This is close to working (though see the notes after the code), though it is far from ideal.
Code:
Private Sub FormPerfil_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim querry As String = "Select Username, PalavraPasse From tblUsers where Username = ? And PalavraPasse = ?"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Users.accdb"
Using conn = New OleDbConnection(dbsource)
Using Cmd As OleDbCommand = conn.CreateCommand
conn.Open()
Cmd.CommandText = querry
Cmd.Parameters.AddWithValue("@p1", txtUser.Text)
Cmd.Parameters.AddWithValue("@p2", txtPassword.Text)
Try
Using dr As OleDbDataReader = Cmd.ExecuteReader()
If dr.Read() Then
txtNomePerfil.Text = dr(1).ToString
Else
txtNomePerfil.Text = "Unknown"
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
As you may note, this is code copied directly from the other snippet you have, with very few changes. It won't quite work as written, though, because you don't have the two textboxes to use for supplying the parameters. A minor change is needed, but that minor change opens up a much better alternative.
The minor change is that you have to get the text from the textboxes to this new form. There are a couple of ways you can do this:
1) Give the new form a constructor that takes two arguments (username and password) and supply those to the form.
2) Give the form a pair of public properties, one for the user name and one for the password, and before you show the form, pass the username and properties from the first form to the second form in the properties.
3) Give the original form a pair of public properties for the user name and password, in which case the second form can go back to the original (if it can find it) and get the values. This can be problematic, because the second form probably doesn't know about the first form, and probably should not know about the first form, in which case the second form wouldn't know where it had to go to get the data.
If I had to pick from those three, I'd use the first option, but if I didn't have to pick from those three, I wouldn't do any of these. After all, every one of them requires that the username and password be provided to the second form, then the second form goes back to the database to do exactly the same thing that it did the first time. That's a total waste of time.
What I would do would be to change the SQL query on the first form to get all the fields that you wanted. Right now, it returns Username and PalavraPasse, but if you have the other fields that you mentioned, then get those as well. Put form level variables on that first form for each of these. Then, if the datareader returns a record, fill those form level variables from the datareader row in that first form. Therefore, if there is no match for the username and password, you get the message saying that the user doesn't exist, but if there IS a match, then you get all the data for that user and put it into form level variables.
Then, when you create the second form, you pass all the data to the constructor of the second form such that the second form already has the data and doesn't need to go back to the database to get it.
My usual boring signature: Nothing
 
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|