I'm trying to show the user role once the login success, but, I cannot obtain the behavior that I want. I'm a beginner and here a put my piece of code what I'm using now.
Sub LoginSistema()
Try
AbrirConexion()
Comando = New SqlCommand("select * from tbl_usuarioslogin where username = '" & frmLoginWindow.TextBox1.Text & "' and password = '" & frmLoginWindow.TextBox2.Text & "'")
Comando.CommandType = CommandType.Text
Comando.Connection = Conexion
Lector = Comando.ExecuteReader()
If Lector.HasRows Then
Lector.Read()
If Lector.GetValue(1).ToString = "Victor" Then
MsgBox("Bienvenido :) " + Lector(8).ToString())
CerrarConexion()
Lector.Close()
Else
MsgBox("Error al iniciar sesion en el Sistema.")
CerrarConexion()
Lector.Close()
End If
Else
MsgBox("No hay datos leidos de la base de datos.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
See ya,
Related
invalid attempt to read when reader is closed error. vb.net
I have the code below that I use to login into MySQL but it keeps displaying the error 'invalid attempt to read when reader is closed' and then it logs in. I don't understand what could still be wrong with the code. Kindly assist, it's so frustrating. Thanks.
Try
ConnDB()
command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
Reader = command.ExecuteReader()
If Reader.Read = True Then
ComboBox1.Text = Reader.GetValue(2)
lblUser.Text = Reader.GetValue(3)
End If
If (Reader IsNot Nothing) Then
Reader.Close()
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
If ComboBox1.Text.Length > 0 Then
MainMenu.lblUserName.Text = Me.txtUsername.Text
MainMenu.lblType.Text = Me.ComboBox1.Text
MainMenu.lblOccupation.Text = Me.ComboBox1.Text
MainMenu.lblUser.Text = Me.lblUser.Text
Dim st As String = "Successfully logged in"
LogFunc(txtUsername.Text, st)
Me.Hide()
MainMenu.Show()
Else
MsgBox("Incorrect username or password..Login is Failed...Try again !", MsgBoxStyle.Critical, "Login")
txtUsername.SelectAll()
txtPassword.SelectAll()
txtUsername.Focus()
txtPassword.Text = ""
End If
command.Dispose()
' Reader.Close()
'command.Dispose()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
DisconnMy()
End Try
I expect it to log in successfully without displaying the error.
Sorry, I forgot to add this for my connection string.
Public Sub ConnDB()
con.Close()
Try
con.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "user id = '" & UserNameMySQL & "'; " _
& "password = '" & PwdMySQL & "'"
con.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
In general it's not a good idea to use a "global", single connection for everything. Note that connection-pooling is enabled by default which means that .NET will take care of the physical connections. So you should create,open,use and close/dispose the connection where you use it.
I'm pretty sure that this will fix the issue:
Try
Using con As New MySql.Data.MySqlClient.MySqlConnection(MySettings.Default.SqlConnection)
Using command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
con.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
ComboBox1.Text = reader.GetValue(2)
lblUser.Text = reader.GetValue(3)
End If
' NOTE: you dont need to close the reader/command/connection
' if you use the Using-statement, it will use Dispose even in case of an error
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
This is a tennis tournament simulation program I'm Trying to make a tree. Everything its working perfectly but I have a big problem. I can't progress to the next stage with the winners of the firts games. Because I can't change the "target" label where I want to write the winners name. Here's a print:
This is how I Generate the winners who is going to the next stage and it actually works.~
Public Sub Gerar_Vencedor(Atleta1, Atleta2)
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" &
"Data Source = E:\dev\Ganso\BaseDados_ClubeTenis.accdb"
con.Close()
con.Open()
Dim busca = "Select Vencedor From Jogo Where idAtleta1 = '" & Atleta1 & "' and idAtleta2 = '" & Atleta2 & "'"
Dim cmd As OleDbCommand = New OleDbCommand(busca, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
' A variável sql vai receber a string para fazer o select a base de dados
'Try
' é aberta ligação a Bdados
' declaração de um comando que vai executar a instrução sql na base de dados
' variável que vai receber os registos resultantes da instrução sql
' ciclo que vai percorrer todos os registos do comando anterior
While dr.Read()
Label9.Text = dr("Vencedor")
End While
con.Close()
End Using
End Sub
My problem is that Label9.Text = dr("Vencedor") because everytime I get a winner it goes to label9.
My final question is: Is there anyway to dynamically change the label without repeating this function over and over.
Thanks.
Can You Try
Dim i As Integer = 9
While dr.Read()
If i < 15
DirectCast(Me.Controls("Label" & i), Label).Text = dr("Vencedor")
Else
End If
i = i + 1
End While
i am trying to open another from login form. but it executes only load event after that both forms get closed.
on button click from login from below is the code
Con.ConnectionString = ConnectionString
Try
Con.Open()
Catch ex As SqlException
' do something with this type of exception
Catch ex As DataException
' do something with this type of exception
Catch ex As Exception
End Try
Dim Sql As String
Dim Pass As String = Module1.EncryptPassword(TxtPassword.Text)
Sql = " select * from c_tpr_users where Usr_name='" & TxtUser.Text & "' and Password='" & Pass & "'"
Dim SC As New SqlCommand
SC.Connection = Con
SC.CommandText = Sql
Dim Sdr As SqlDataReader = SC.ExecuteReader()
If Sdr.HasRows Then
MsgBox("Login Sucess", vbOKOnly + vbInformation)
Sdr.Close()
SC.Dispose()
UserNameInCustomERP = TxtUser.Text
UserNameInERP = TxtUser.Text
Sql = "select Year from FinYears where CONVERT(date, GETDATE())>=StartDate and CONVERT(date, GETDATE())<=EndDate"
SC.Connection = Con
SC.CommandText = Sql
Sdr = SC.ExecuteReader()
If Sdr.HasRows Then
If Sdr.Read() Then
FAYear = Sdr.Item("year")
End If
End If
Sdr.Close()
SC.Dispose()
'new form want to opend
FrmSampleDispatch.Show()
Me.Close()
kindly help me... thanks in advance
I'm programming a dog adoption form. It retrieves data from a Access DB then the user can adopt up to three dogs, each one of them specified in 3 different fields. I'm doing it this way because I previously tried to do it with arrays, with no luck.
The issue comes here (highlighted in bold):
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
cmd.CommandText = "select adopcion1, adopcion2, adopcion3 from usuarios where codigo_usuario = " & FormPrincipal.codigo_usuario & ""
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read()
**If dr.IsDBNull(1) Then
posicionAdopcion = 1
ElseIf dr.IsDBNull(2) Then
posicionAdopcion = 2
ElseIf dr.IsDBNull(3) Then
posicionAdopcion = 3
Else
MsgBox("Lo sentimos, solo puedes hacer un máximo de 3 adopciones")
Exit Sub**
End If
End While
dr.Close()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación.")
Me.Close()
End Try
and
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
**If (posicionAdopcion = 1) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION1 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 2) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION2 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 3) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION3 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
End If**
cmd.ExecuteNonQuery()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación...")
Me.Close()
End Try
What I'm trying to do is to check if the adoption fields (adopcion1, adopcion2, adopcion3) are empty, if they are, place the name of the dog there. If they are not, check for the next free slot. If none available, print the corresponding error message. But what the program does is to overwrite the adopcion1 (first field) no matter what.
I have checked this thread, I may be having a similar issue misunderstanding isDBNull usage, but so far I'm trying to do what it's stated there with no result.
What I'm doing wrong?
I got it, as I expected it was a silly mistake: I was retrieving the first data field from 1, and not from 0. Thus skipping it entirely:
If dr.isDBNull(0) Then
posicionAdopcion = 1
But yes, the code seems clunky, didn't know about SQL parameters, going to check them ASAP.
Thanks for the help!
Well I'm creating a search bar to find some patients in my school project, but when I search it works, but when I made another search it sent me the message as if the number dont exist even when it exist, this is the code of the button hope you can help me.
Private Sub cmdIDBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBuscarID.Click
Dim sqlCon As New SqlClient.SqlConnection
Dim sqlComm As New SqlClient.SqlCommand
'Ruta de la conección.
sqlCon.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Sistema para Hospitales.mdf;Integrated Security=True;User Instance=True")
'Instrucción con la que se trabajara.
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= '" & txtID.Text & "';"
'Abrir la coneccion SQL
sqlCon.Open()
Do Until txtID.Text = txtCompararID.Text
Me.PacientesBindingSource.MoveNext()
Exit Do
If EOF(True) Then KryptonMessageBox.Show("Error, no se encontro paciente.", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
Loop
If txtID.Text = txtCompararID.Text Then
txtNombres.Text = txtCompararN1.Text & " " & txtCompararN2.Text & " " & txtCompararN3.Text
txtApellidos.Text = txtCompararAp1.Text & " " & txtCompararAp2.Text
txtEdad.Text = txtCompararEdad.Text
Select Case txtCompararSexo.Text
Case Is = "F"
txtSexo.Text = "Femenino"
Case Is = "M"
txtSexo.Text = "Masculino"
End Select
Select Case TipoAfiliacionTextBox.Text
Case Is = "1"
txtTAfiliacion.Text = "Cotizante"
Case Is = "2"
txtTAfiliacion.Text = "Beneficiario"
Case Is = "3"
txtTAfiliacion.Text = "Pensionado"
End Select
txtAltura.Text = AlturaTextBox1.Text
txtPeso.Text = PesoTextBox1.Text
txtPresion.Text = PresionTextBox.Text
txtTemperatura.Text = TemperaturaTextBox.Text
Else
KryptonMessageBox.Show("No se encontro el paciente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Among other problems, because you have an Exit Do statement in the middle of your comparison loop, you will probably only ever match the first record since your do loop will execute a maximum of one time.
I am guessing that txtCompararID is databaound to your PacientesBindingSource and that the intent of your loop is move through this binding source until you find the value that matches txtID.
If that is the case, your do loop should look something more like:
' Get back to the top of the list
Me.PacientesBindingSource.MoveFirst()
Do Until txtID.Text = txtCompararID.Text
Me.PacientesBindingSource.MoveNext()
If EOF(True) Then
KryptonMessageBox.Show("Error, no se encontro paciente.", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
Exit Do
End If
Loop
In addition, you should use Using statements for your connection and command objects so that they are properly closed and disposed of when you are done using them.
For example:
Using sqlCon As New SqlClient.SqlConnection
Using sqlComm As New SqlClient.SqlCommand
... all of your code
End Using
End Using
And finally, and most importantly, you should be using a parameterized query statement in order to prevent SQL injection attacks since you are allowing direct entry of values. This statement:
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= '" & txtID.Text & "';"
should be changed to something like:
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= ?"
sqlComm.Parameters.AddWithValue("IDPaciente", txtID.text)