Database query not returning results from value - vb.net

I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
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 OleDbCommand(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 OleDbDataAdapter(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 params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class

Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.

Related

Save a DataGridView data to Access database

I am trying to save a DataGridView data to an Access database (database is already connected to Visual Studio).
Here's my code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Dim cn As OleDbConnection
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;")
cn.Open()
Dim cmd As New OleDbCommand
cmd.Connection = cn
cmd.CommandType = Data.CommandType.Text
Dim Strcommandtext As String = "inserto into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao) VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#Data_de_Emissao)"
Dim values As String = ""
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
values = Strcommandtext & Factura2DataGridView.Rows(i).Cells(11).Value & ")"
cmd.CommandText = values
cmd.ExecuteNonQuery()
Next i
cmd = Nothing
cn.Close()
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.ToString())
Finally
'MsgBox("Closing Connection")
End Try
End Sub
Connections and Commands need to be disposed so they can release unmanaged resources. Using...End Using blocks are the best way to handle this since the will do this even if there is an error. In this code I both the connection and command are included in the Using block. Note the comma at the end of the first Using line.
Pass the CommandText and the Connection directly to the constructor of the command. I noticed you had missed one of the parameters that was in the field list. I also noticed the you typed "inserto". I believe it must be "Insert". It is not necessary to set CommandType since CommandType.Text is the default.
In OleDb the order that the parameters appear in the sql string must match the order that they are added to the Parameters collection.
Build the parameters collection once outside the loop. It is only the Values of the parameters that change in the loop.
Open the connection once, outside the loop.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;"),
cmd As New OleDbCommand("Insert into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao)
VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#CodigoProduto,#Data_de_Emissao)", cn)
With cmd.Parameters
.Add("#Servico_Produto", OleDbType.Integer)
.Add("#Valor", OleDbType.VarWChar)
.Add("#Qtd", OleDbType.Integer)
.Add("#Total", OleDbType.Decimal)
.Add("#Nome", OleDbType.VarWChar)
.Add("#Entidade", OleDbType.VarWChar)
.Add("#NIF", OleDbType.VarWChar)
.Add("#Telemovel", OleDbType.VarWChar)
.Add("#Bairro", OleDbType.VarWChar)
.Add("#CodigoProduto", OleDbType.Integer)
.Add("#Data_de_Emissao", OleDbType.Date)
End With
cn.Open()
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
cmd.Parameters("#Servico_Produto").Value = Factura2DataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#Valor").Value = Factura2DataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Qtd").Value = Factura2DataGridView.Rows(i).Cells(2).Value
cmd.Parameters("#Total").Value = Factura2DataGridView.Rows(i).Cells(3).Value
cmd.Parameters("#Nome").Value = Factura2DataGridView.Rows(i).Cells(4).Value
cmd.Parameters("#Entidade").Value = Factura2DataGridView.Rows(i).Cells(5).Value
cmd.Parameters("#NIF").Value = Factura2DataGridView.Rows(i).Cells(6).Value
cmd.Parameters("#Telemovel").Value = Factura2DataGridView.Rows(i).Cells(7).Value
cmd.Parameters("#Bairro").Value = Factura2DataGridView.Rows(i).Cells(8).Value
cmd.Parameters("#CodigoProduto").Value = Factura2DataGridView.Rows(i).Cells(9).Value
cmd.Parameters("#Data_de_Emissao").Value = Factura2DataGridView.Rows(i).Cells(10).Value
cmd.ExecuteNonQuery()
Next
End Using
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.Message)
End Try
End Sub
There are easier ways to do this. If you have a DataTable bound to the DataGridView you can use a DataAdpater.Update method.

How to Update my Access Database from textboxes

i created a screen where i can edit the details in the database. but as soon as i click on the update button, it says no value given for one or more required parameters. i have attached my code....
Update BUtton...
Private Sub SimpleButton5_Click(sender As Object, e As EventArgs) Handles SimpleButton5.Click
Try
Access.AddParam("#UId", TextBox1.Text)
Access.AddParam("#ImagePic", PictureBox1.Image)
Access.AddParam("#Barcod", TextBox2.Text)
Access.AddParam("#BrandName", TextBox3.Text)
Access.AddParam("#StockName", TextBox4.Text)
Access.AddParam("#Category", TextBox5.Text)
Access.AddParam("#SubCat", TextBox6.Text)
Access.AddParam("#Subcat2", TextBox7.Text)
Access.AddParam("#Discrip", TextBox8.Text)
Access.AddParam("#StockLvl", TextBox9.Text)
Access.AddParam("#CustomAmount", TextBox10.Text)
Access.AddParam("#CostPrice", TextBox11.Text)
Access.AddParam("#Markup", TextBox12.Text)
Access.AddParam("#TaxAmount", TextBox13.Text)
Access.AddParam("#SellingPrice", TextBox14.Text)
Access.AddParam("#BeforTax", TextBox15.Text)
Access.AddParam("#AfterTax", TextBox16.Text)
Access.AddParam("#TaxPer", TextBox17.Text)
Access.AddParam("#MarkupPer", TextBox18.Text)
Access.AddParam("#LastDate", TextBox19.Text)
Access.AddParam("#LastUser", TextBox20.Text)
Access.ExecQuery("UPDATE Inventory " &
"SET [Image]=PictureBox1.image, BarCode=Textbox2.text, " &
"BrandName=#BrandName, StockName=#StockName, Category=#Category, SubCategory=#SubCat, " &
"SubCategory2=#SubCat2, Description=#Discrip, StockLevels=#StockLvl, CustomAmount=#Customamount, " &
"CostPrice=#CostPrice, MarkupAmount=#Markup, SellingPrice=#SellingPrice, ProfirBefore=#BeforeTax, " &
"ProfitAfter=#AfterTax, TaxAmount=#TaxAmount, taxPer=#TaxPer, MarkupPer=#MarkupPer, LastDateupdated=#LAstDate, " &
"UpserUpdated=#LastUser WHERE ID=#UId")
If NoErrors(True) = False Then Exit Sub
RefreshData()
Catch ex As Exception
MsgBox(ex.Message)
Finally
End Try
End Sub
My Access.ExecQuery --- (Class...)
Imports System.Data.OleDb
Public Class DBControl
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;")
Private DBCmd As OleDbCommand
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
Public Params As New List(Of OleDbParameter)
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
RecordCount = 0
Exception = ""
Try
DBCon.Open()
DBCmd = New OleDbCommand(Query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
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 OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
I have played around with this for 2 days now, but somewhere i am missing something or overlooking something
thx
Jaco
The error message is pretty obvious. Some parameters are missing, either you forgot them or they are misspelled.
You need to double-check your code, it contains quite a few typos.
You are defining parameter #ImagePic, but it's not used in your query.
Same for #Barcod, you put this instead in your SQL: BarCode=Textbox2.text. Just call it #Barcode, why do you abbreviate names like that. That only creates confusion. Use proper English spelling and be consistent.
Another typo: Access.AddParam("#BeforTax", TextBox15.Text). In your SQL: ProfirBefore=#BeforeTax. ProfirBefore is a typo too.
Please do yourself a favor and rename the textboxes too: TextBox1 thru 20 is not good naming practice. There is good chance that you will mix up fields after doing copy-paste of your statements. Textbox20 is not intuitive at all and does not tell you what data you are handling.
I have played around with this for 2 days now, but somewhere i am missing something or overlooking something
Missing glasses perhaps :) I don't know about your development environment put I pasted your code in Notepad++ and by clicking on a keyword it highlights all occurrences of that keyword in the code. It quickly became obvious that some keywords were not being referenced anywhere.
I created a simple class for your Inventory object so I could avoid passing all of Properties as parameters. I can just pass the Inventory object to the UpdateDatabase method.
Public Class Inventory
Public Property Picture As Byte()
Public Property BarCode As String
Public Property BrandName As String
Public Property StockName As String
Public Property Category As String
Public Property SubCategory As String
Public Property SubCategory2 As String
Public Property Description As String
Public Property StockLevels As Integer
Public Property CustomAmount As Decimal
Public Property CostPrice As Decimal
Public Property MarkupAmount As Decimal
Public Property SellingPrice As Decimal
Public Property ProfitBefore As Decimal
Public Property ProfitAfter As Decimal
Public Property TaxAmount As Decimal
Public Property taxPer As Decimal
Public Property MarkupPer As Decimal
Public Property LastDateupdated As Date
Public Property UpserUpdated As String
Public Property ID As Integer
End Class
To get your picture box image in the proper format for storage I have a small function that takes an Image as a parameter and returns a Byte array.
'This Function requires Imports System.Drawing
Private Function GetByteArrayFromImage(img As Image) As Byte()
Dim convert As New ImageConverter
Dim arr = DirectCast(convert.ConvertTo(img, GetType(Byte())), Byte())
Return arr
End Function
Each property of the Inventory object is set. You can see that giving your controls meaningful names would help here. CInt, CDec, and CDate text boxes need to be validated before this code is reached.
I put the Try...Catch here so you could show a message to the user.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim img As Image = PictureBox1.Image
Dim imgArray = GetByteArrayFromImage(img)
Dim inv As New Inventory With
{
.Picture = imgArray,
.BarCode = TextBox2.Text,
.BrandName = TextBox3.Text,
.StockName = TextBox4.Text,
.Category = TextBox5.Text,
.SubCategory = TextBox6.Text,
.SubCategory2 = TextBox7.Text,
.Description = TextBox8.Text,
.StockLevels = CInt(TextBox9.Text),
.CustomAmount = CDec(TextBox10.Text),
.CostPrice = CDec(TextBox11.Text),
.MarkupAmount = CDec(TextBox12.Text),
.SellingPrice = CDec(TextBox14.Text),
.ProfitBefore = CDec(TextBox15.Text),
.ProfitAfter = CDec(TextBox16.Text),
.TaxAmount = CDec(TextBox13.Text),
.taxPer = CDec(TextBox17.Text),
.MarkupPer = CDec(TextBox18.Text),
.LastDateupdated = CDate(TextBox19.Text),
.UpserUpdated = TextBox20.Text,
.ID = CInt(TextBox1.Text)
}
Try
UpdateDatabase(inv)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
In Access the order that the parameters appear in the sql statement must match the order that they are added to the parameters collection.
I thought it was odd that all your field names are capitalized except taxPer. Check your database.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
The .Add method is superior to the method you were using because it includes datatypes and size. I had to guess at the types and sizes so check your database. Where I have guessed wrong, you will have to correct the .Add method, the type of the property in the Inventory class and the conversion of the text boxes .Text property. (3 places to change)
Private Sub UpdateDatabase(inv As Inventory)
Dim sql = "UPDATE Inventory SET
[Image]=#Picture,
BarCode= #BarCode,
BrandName=#BrandName,
StockName=#StockName,
Category=#Category,
SubCategory=#SubCat,
SubCategory2=#SubCat2,
Description=#Discrip,
StockLevels=#StockLvl,
CustomAmount=#Customamount,
CostPrice=#CostPrice,
MarkupAmount=#Markup,
SellingPrice=#SellingPrice,
ProfirBefore=#BeforeTax,
ProfitAfter=#AfterTax,
TaxAmount=#TaxAmount,
taxPer=#TaxPer,
MarkupPer=#MarkupPer,
LastDateupdated=#LAstDate,
UpserUpdated=#LastUser
WHERE ID=#UId"
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;"),
cmd As New OleDbCommand(sql, cn)
With cmd.Parameters
.Add("#Picture", OleDbType.LongVarBinary).Value = inv.Picture
.Add("#BarCode", OleDbType.VarChar, 100).Value = inv.BarCode
.Add("#BrandName", OleDbType.VarChar, 100).Value = inv.BrandName
.Add("#StockName", OleDbType.VarChar, 100).Value = inv.StockName
.Add("#Category", OleDbType.VarChar, 100).Value = inv.Category
.Add("#SubCat", OleDbType.VarChar, 100).Value = inv.SubCategory
.Add("#SubCat2", OleDbType.VarChar, 100).Value = inv.SubCategory2
.Add("#Discrip", OleDbType.VarChar, 100).Value = inv.Description
.Add("#StockLvl", OleDbType.Integer).Value = inv.StockLevels
.Add("#Customamount", OleDbType.Decimal).Value = inv.CustomAmount
.Add("#CostPrice", OleDbType.Decimal).Value = inv.CostPrice
.Add("#Markup", OleDbType.Decimal).Value = inv.MarkupAmount
.Add("#SellingPrice", OleDbType.Decimal).Value = inv.SellingPrice
.Add("#BeforeTax", OleDbType.Decimal).Value = inv.ProfitBefore
.Add("#AfterTax", OleDbType.Decimal).Value = inv.ProfitAfter
.Add("#TaxAmount", OleDbType.Decimal).Value = inv.TaxAmount
.Add("#TaxPer", OleDbType.Decimal).Value = inv.taxPer
.Add("#MarkupPer", OleDbType.Decimal).Value = inv.MarkupPer
.Add("#LAstDate", OleDbType.Date).Value = inv.LastDateupdated
.Add("#LastUser ", OleDbType.VarChar, 100).Value = inv.UpserUpdated
.Add("#UId", OleDbType.Integer).Value = inv.ID
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue