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)
Related
I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```
It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function
For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if
My app in VB.Net loads data from MS Access in a datagridview (bound with a BindingSource, but result/problem is the same if that's a DataTable).
Private Sub LecturesPrestations()
Dim myConnection = New OleDbConnection(S7ConnString)
Try
myConnection.Open()
Requete = "SELECT s.ID, u.Nom, s.DatePresta, s.TimeIn, s.TimeOut, IIF(s.TimeOut IS NULL, NULL, CDATE(s.TimeOut - s.TimeIn)) AS Duree, s.Description " &
"FROM SAV_Prestas AS s " &
"INNER JOIN Users AS u ON u.ID = s.UserID " &
"WHERE s.NumRMA = " & monRetour.ID & ";"
Call GetBindingSource(Requete, bsPrestas, RequeteOK)
If Not RequeteOK Then
MsgBox("Problème de lecture des données",, "Chargement des prestations")
Else
With Me.dgvPresta
.DataSource = bsPrestas
...
We can then insert, delete or modifiy a row in this dgv by explicit Access instructions (INSERT, DELETE, UPDATE...). The dgv is then refreshed (reload), to include these modifications.
Private Sub tsmiSuppression_Click(sender As Object, e As EventArgs) Handles tsmiSuppression.Click
If dgvPresta.CurrentCell IsNot Nothing Then
Requete = "DELETE * FROM SAV_Prestas WHERE ID = " & CInt(dgvPresta.Item("ID", dgvPresta.CurrentCell.RowIndex).Value.ToString)
RequeteSQL(Requete, RequeteOK)
If Not RequeteOK Then
MsgBox("La prestation n'a pas pu être supprimée.")
Else
Call LecturesPrestations()
End If
Else
MsgBox("Sélectionnez une prestation.", vbOKOnly, vbInformation)
End If
End Sub
Public Sub RequeteSQL(ByVal Request As String, ByRef Resultat As Boolean, Optional ByRef MsgErreur As String = Nothing)
Dim myConnection = New OleDb.OleDbConnection(S7ConnString)
Try
myConnection.Open()
Dim myCommand = New OleDbCommand(Request, myConnection)
myCommand.ExecuteNonQuery()
Resultat = True
Catch ex As Exception
Resultat = False
MsgErreur = ex.Message
Finally
myConnection.Close()
End Try
End Sub
In this way, the dgv does not display the modified data (example: deleted data still appears). It is only after a new "refresh" a few seconds later that the modifications appear.
Have you any idea what's wrong and how to solve this?
Thank you.
Have you tried to refresh your datagridview after SQL Query?
Call dgvPresta.refresh() after "Call LecturesPrestations()"
Connection performance to your DB and size might be the problem.
I'm doing a VB with Access database and I want to create a button. Which savebutton with checking where the data that try to insert is duplicated or not compare with my database.
This my code, and the problem is whatever I enter it just show the user already exists.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
If (ComboBox2.Text = "") And (ComboBox3.Text = "")
And (TextBox3.Text = "") And (ComboBox4.Text = "")
Then
MsgBox("Please fill-up all fields!")
Else
Dim theQuery As String = ("SELECT * FROM Table1
WHERE"" [Subject_Code]=#Subject_Code ,[Day]=#Day,
[Times]=#Times , [Lecture]=#Lecture and [Class_Room]=#Class_Room""")
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, MyConn)
cmd1.Parameters.AddWithValue("#Subject_Code", TextBox6.Text)
cmd1.Parameters.AddWithValue("#Day", ComboBox2.Text)
cmd1.Parameters.AddWithValue("#Times", ComboBox3.Text)
cmd1.Parameters.AddWithValue("#Lecture", TextBox3.Text)
cmd1.Parameters.AddWithValue("#Class_Room", ComboBox4.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'User already exists
MsgBox("User Already Exist!")
Else
Dim Update As String = "INSERT INTO [Table1]
([Subject_Code], [Subject],
[Day], [Times], [Level],[Semester], [Lecture],[Class], [Class_Room])
VALUES (?,?,?,?,?,?,?,?,?)"
Using cmd = New OleDbCommand(Update, MyConn)
cmd.Parameters.AddWithValue("#p1", TextBox6.Text)
cmd.Parameters.AddWithValue("#p2", TextBox1.Text)
cmd.Parameters.AddWithValue("#p3", ComboBox2.Text)
cmd.Parameters.AddWithValue("#p4", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p5", ComboBox1.Text)
cmd.Parameters.AddWithValue("#p6", ComboBox6.Text)
cmd.Parameters.AddWithValue("#p7", TextBox3.Text)
cmd.Parameters.AddWithValue("#p8", ComboBox5.Text)
cmd.Parameters.AddWithValue("#p9", ComboBox4.Text)
MsgBox("New Data Is Saved")
cmd.ExecuteNonQuery()
End Using
End If
End Using
End If
First of all take a quick look at your theQuery variable, it may just have been malformed from where you have typed it into SO, but if not try:
Dim theQuery As String = "SELECT * FROM Table1 " &
"WHERE [Subject_Code] = #Subject_Code " &
"AND [Day] = #Day " &
"AND [Times] = #Times " &
"AND [Lecture] = #Lecture " &
"AND [Class_Room] = #Class_Room"
Your check for a pre existing user is based upon 5 fields, the insert for new data has 9 fields. Without knowing the business case I can't be sure if this is correct or if the missing 4 fields are actually important to the check and causing unexpected rows to be returned.
Personally my next steps would be:
Put a breakpoint on the AddWithValue statements and check the values
are what you expect
Run the query with the values in SSMS/Access or equivalent and check the rows that come back are what you expect
I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID
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!