Use VB.NET Manipulate Microsoft Access Database - vb.net

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks

Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub

Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

Related

Access Database VB - Searching a database for most 'RECENT' record

I was wondering how I could change the code below, to allow me to search for the most recent record. I am creating a Hotel Booking System and want to use the most recent price in the database but at the moment, it is just searching using the labels which I don't want.
Dim str1 As String
Dim dbpassword As String = "123"
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= E:\Computing\Hotel Booking System\Database\Hotel Booking System.accdb ;Jet OLEDB:Database Password =" & dbpassword & ";"
Dim MyConn As OleDbConnection
Dim dr As OleDbDataReader
Private Sub Information_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim PriceFound As String = False
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
str1 = ("SELECT * FROM [Prices] WHERE [Adult] = '" & LblPriceAdult.Text & "' AND [Child] = '" & LblPriceChild.Text & "'")
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
dr = cmd1.ExecuteReader
While dr.Read()
PriceFound = True
DateDisplay = dr("ID").ToString
AdultPrice = dr("Adult").ToString
ChildPrice = dr("Child").ToString
SingleRoom = dr("Single").ToString
DoubleRoom = dr("Double").ToString
FamilyRoom = dr("Family").ToString
If PriceFound = True Then
LblPriceAdult.Text = AdultPrice
LblPriceChild.Text = ChildPrice
LblPriceDoubleRoom.Text = DoubleRoom
LblPriceFamilyRoom.Text = FamilyRoom
LblPriceSingleRoom.Text = SingleRoom
End If
End While
MyConn.Close()
End Sub
Based on your previous comments, you need to rewrite your SQL to trap the most recent record.
Try something like this:
SELECT MAX(ID) FROM [Prices] ORDER BY ID DESC
I tried the answer above. However for the code above, it wouldn't search for the most recent so I changed DESC to ASC

LogIn form with user and admin using VB.net and Mysql

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

Duplicated Records on DataGridView - closed

How can I remove the duplicated records showing in the DataGridView? When I try to search for a record with for example the keyword "dev", the DataGridView will display all the records with "dev" in them, row 1 to 15 have "dev" in them, BUT, after the 15th row, there is another set of records which is exactly the same as the 1st row to 15th row. How can I remove these?
The whole image is confidential so I cropped it to the minimum size possible.
Imports System.Data.OleDb
Imports System.IO
Imports System.Drawing.Printing
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet.Tasks_Of_Offices' table. You can move, or remove it, as needed.
Me.Tasks_Of_OfficesTableAdapter.Fill(Me.Database1DataSet.Tasks_Of_Offices)
'TODO: This line of code loads data into the 'Database1DataSet.Roadmap' table. You can move, or remove it, as needed.
Me.RoadmapTableAdapter.Fill(Me.Database1DataSet.Roadmap)
'TODO: This line of code loads data into the 'Database1DataSet.Project' table. You can move, or remove it, as needed.
Me.ProjectTableAdapter.Fill(Me.Database1DataSet.Project)
'TODO: This line of code loads data into the 'Database1DataSet.OPR' table. You can move, or remove it, as needed.
Me.OPRTableAdapter.Fill(Me.Database1DataSet.OPR)
Me.WindowState = FormWindowState.Maximized
End Sub
Private Sub btnserch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnserch.Click
Search_Record()
End Sub
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim sSQL As String = String.Empty
'try catch block is used to catch the error
Try
'get connection string declared in the Module1.vb and assign it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Name like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Manager like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Office like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
sSQL = "SELECT ContactNr, Researcher FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where ContactNr like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Researcher like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Initiatives like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.projectdg.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
So, waiting for an answer made my hair white. I've already found an answer to my question. so i add a code in this part
sSQL = "SELECT ID, Name, Manager, Office, ContactNr, Researcher, Initiatives FROM [Project]"
If Me.cbSearch.Text = "Project" Then
sSQL = sSQL & "where Name like '%" & Me.sbox.Text & "%'"
projectdg.Visible = True
oprdg.Visible = False
rmdg.Visible = False
toodg.Visible = False
Else
MsgBox("No Record Found")
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
which is RemoveDuplicateRows(dt, "nameofcolumn")
and added another code which is this one,
Public Function RemoveDuplicateRows(ByVal dTable As DataTable, ByVal colName As String) As DataTable
Dim hTable As New Hashtable()
Dim duplicateList As New ArrayList()
For Each dtRow As DataRow In dTable.Rows
If hTable.Contains(dtRow(colName)) Then
duplicateList.Add(dtRow)
Else
hTable.Add(dtRow(colName), String.Empty)
End If
Next
For Each dtRow As DataRow In duplicateList
dTable.Rows.Remove(dtRow)
Next
Return dTable
End Function

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

Retrieving/adding data from/to a stored procedure

Alright so I have this webpage that I have to create and it has 3 pages and a master page. Now basically all of it is working, except the fact that I can't seem to get data coming into the webpage when requested via a retrieve button, nor will it update or add data to the SQL table. Now in my queries page when I put Select * From Customer it brings back the data in the table so that part works. From what I have to work with in the pdf's provided, they want me to use
TextBox1.Text = table.Rows(0).Field<string>("TextBox1")
TextBox1.DataBind()
To retrieve the data from the sql, now it comes up with an error saying Overload resolution failed because no accessible 'Field' accepts this number of arguments.
So here is my Customer page
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.DataRowCollection
Public Class Customer
Inherits System.Web.UI.Page
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Shadows adapter As SqlDataAdapter = New SqlDataAdapter()
// Tells me to use Shadows because variable adapter conflicts with property 'adapter'
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand()
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
conn = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Dim command As SqlCommand = New SqlCommand()
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = "INSERT INTO Acme_Customer VALUES(" & txtCustID.Text & ",'" & txtFirstname.Text & "', '" & txtSurname.Text & "', " & txtGender.Text & ", " + txtAge.Text & ", " & txtAddress1.Text & ", " & txtAddress2.Text & ", " & txtCity.Text & ", " + txtPhone.Text & ", " + txtMobile.Text & ", " & txtEmail.Text & ")"
command.Connection.Open()
adapter.InsertCommand = command
adapter.InsertCommand.ExecuteNonQuery()
command.Connection.Close()
Clear()
lblMessage.Text = "You have been successfully added into our records"
Catch ex As Exception
lblMessage.Text = "Something has gone wrong with adding you to our records, please double check everything as we want you to become a member."
End Try
End Sub
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
txtFirstname.Text = table.Rows(0).Field<string>("Firstname")
txtFirstname.DataBind()
txtSurname.Text = table.Rows(0).Field<string>("Surname")
txtSurname.DataBind()
txtGender.Text = table.Rows(0).Field<String>("Gender")
txtGender.DataBind()
txtAge.Text = table.Rows(0).Field<Integer>("Age")
txtAge.DataBind()
txtAddress1.Text = table.Rows(0).Field<String>("Address1")
txtAddress1.DataBind()
txtAddress2.Text = table.Rows(0).Field<String>("Address2")
txtAddress2.DataBind()
txtCity.Text = table.Rows(0).Field<String>("City")
txtCity.DataBind()
txtPhone.Text = table.Rows(0).Field<Integer>("Phone Number")
txtPhone.DataBind()
txtMobile.Text = table.Rows(0).Field<Integer>("Mobile Number")
txtMobile.DataBind()
txtEmail.Text = table.Rows(0).Field<String>("Email")
txtEmail.DataBind()
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub
So I'm just wondering what I've written wrong or if I should be using other code instead of what I have here, I know I should be using C# but I just got the hang of vb so, hopefully I can just start using C# after this project.
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
dim objDV as dataview = table.defaultview
txtFirstname.Text = objDV(0)("Firstname").tostring
txtSurname.Text = objDV(0)("Surname").tostring
' Fill all other text boxes following above lines
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub