Access VBA DLookup Multiple Critiera based on Variables - vba

I've been poking around with the below code and cannot get it to work.
Dim db As Database
Dim RecRLs As Recordset
Dim sTripCode, sVanNum As Integer
Dim sDepDate, sArrivalDate As Date
Dim sRoomRate As Currency
Set RecRLs = db.OpenRecordset("qryRLRoomListRates", dbOpenSnapshot)
sTripCode = DLookup("[TourCodeID]", "tblTripCodes", "[TourCode]=[Forms]![frmRMSBuildRLs]![tboxTourCode]")
sDepDate = [Forms]![frmRMSBuildRLs]![tboxDepartureDate]
sVanNum = [Forms]![frmRMSBuildRLs]![tboxVanNumber]
sArrivalDate = RecRLs!ArrivalDate
sRoomRate = DLookup("[RateTwinHosCab]", "tblRLRatesByTrip", "[TourCode] = "
& sTripCode & " AND [DepartureDate] = " & sDepDate & " AND [VanNumber] = " &
sVanNum & " AND [ArrivalDate] = " & sArrivalDate)
The issue is that sRoomRate returns null.
I've MsgBox'd each of the variables: sTripCode, sDepDate, sVanNum, and sArrivalDate. They each return the correct result.
Any ideas why sRoomRate would return null? Thank you so much!

The solution was to add the #s around the dates below:
sRoomRate = DLookup("[RateTwinHosCab]", "tblRLRatesByTrip", "[TourCode] = " &
sTripCode & " AND [DepartureDate] = #" & sDepDate & "# AND [VanNumber] = " &
sVanNum & " AND [ArrivalDate] = #" & sArrivalDate & "#")

Related

Search button using more than one text field Access vba

This is my code below. I am trying to search a database using two different dates, company name
I am getting an error when one of the date fields is empty or null. How can I solve this issue or bypass if the date search field is empty to ignore it in the search or search for an empty field?
Dim SQL As String
SQL = "SELECT * from qryRequestInternal where ([DateRequestSent] = #" & txt_Search_Sdate & "# AND [DateReceived] = #" & txt_Search_Rdate & "# AND (companyName like ""*" & txt_SCompNa & "*"") )"
Me.sfrmRequestInternal.Form.RecordSource = SQL
Me.sfrmRequestInternal.Form.Requery
Me.sfrmRequestInternal_col.Form.RecordSource = SQL
Me.sfrmRequestInternal_col.Form.Requery
End Sub
You will need to check for Null values and build the SQL string based on the controls which have a value (i.e. not null).
The example below uses a helper function to build the sql string. If nothing is inserted, it will only run the the Select * from qryRequestInternal without any criteria.
Private Function SqlWhere() As String
Dim retvalue As String
'sent date
With txt_Search_Sdate
If Not IsNull(.Value) Then
retvalue = " WHERE [DateRequestSent] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'received date
With txt_Search_Rdate
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [DateReceived] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'company
With txt_SCompNa
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [companyName] Like '*" & .Value & "*'"
End If
End With
SqlWhere = retvalue
End Function
To call it:
Dim sqlString As String
sqlString = "SELECT * from qryRequestInternal" & SqlWhere()
Debug.Print sqlString

VBA RecordSet function takes too much time to update record using RecordCount

I have one table and one query. Both have the same data field but table COLUMN names are equal to query's ROW name. I update table from query's row data using the following code successfully but it takes too much time to update as there are more than 50 columns name in the table for each employee-
Set rst1 = CurrentDb.OpenRecordset("SELECT * FROM tblPayRollDataTEMP")
Set rst2 = CurrentDb.OpenRecordset("SELECT * FROM qryEmpVerifySalary ")
Do Until rst1.EOF
rst2.MoveFirst
Do Until rst2.EOF
For l = 0 To rst1.Fields.count - 1
If rst1!EmpID = rst2!EmpID And rst1.Fields(l).Name = rst2!Head And rst1!PayBillID = TempVars!BillID Then
With rst1
rst1.Edit
rst1.Fields(l).Value = rst2!Amount
rst1!totDeductions = DSum("Amount", "qryEmpVerifySalary", "[PayHeadType] = 'Deductions' AND [EmpID] = " & rst2!EmpID & "") + DLookup("NPS", "qryEmpPayEarning", "[EmpID] = " & rst2!EmpID & "")
rst1!totRecoveries = DSum("Amount", "qryEmpVerifySalary", "[PayHeadType] = 'Recoveries' AND [EmpID] = " & rst2!EmpID & "")
rst1!NetPayable = rst1!totEarnings - (Nz(rst1!totDeductions, 0) + Nz(rst1!totRecoveries, 0))
rst1.Update
End With
End If
Next
rst2.MoveNext
Loop
rst1.MoveNext
Loop
Set rst1 = Nothing
Set rst2 = Nothing
How to improve the performance of the code?
You should use a query to update your records. This would be the fastest solution. Normally one would match the EmpID and drag and drop the fields into the update query or use an expression. If you have to group before or other complex stuff split it in more querys (two or three). It doesnt matter thou, because in the end you just execute one update query.
For your code, you can replace the domainaggregate functions. DLookup(), DSum(), etc... these are worst for performance. A simple select statement runs way faster than DLookup(). Here are a few replacements:
Function DCount(Expression As String, Domain As String, Optional Criteria) As Variant
Dim strSQL As String
strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'Other Replacements:
'DLookup: strSQL = "SELECT " & Expression & " FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DCount = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
End Function

Run-time error '3144': Syntax Error in Update Statement

I'm running into some issues with my update statement, the Add statement seems to work but I keep getting a syntax error in update. I am new to SQL and VBA so a lot of this probably looks like sphagetti code. If anyone can Identify what I did wrong that would be much appreciated. If there is a better way to do it, please let me know.
Private Sub btnSubmit_Click()
Dim mbrName As String
Dim mbrOffice As String
Dim mbrRank As String
Dim mbrOpType As String
Dim mbrRLA As String
Dim mbrMQT As String
Dim mbrPos As String
Dim sqlAdd As String
Dim sqlUpdate As String
If Me.opgMngRoster.Value = 1 Then
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'ADD MEMBER TO ROSTER
sqlAdd = "INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
DoCmd.RunSQL (sqlAdd)
'-Confirmation Msg
MsgBox ("Added: " & mbrName)
Else
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'Update Member Data
sqlUpdate = "UPDATE [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
Debug.Print sqlUpdate
DoCmd.RunSQL sqlUpdate
MsgBox ("Updated: " & mbrName)
End If
End Sub
Several general coding and specific MS Access issues with your setup:
First, no need to repeat your VBA variable assignments for both If and Else blocks. Use DRY-er code (Don't Repeat Yourself).
Also, since you do not apply further calculations, there is no need to assign the majority of form textbox and combobox values to separate string variables. Use control values directly in query.
Use parameterization (an industry best practice) which is not only for MS Access but anywhere you use dynamic SQL in an application layer (VBA, Python, PHP, Java, etc.) for any database (Postgres, SQL Server, Oracle, SQLite, etc.). You avoid injection and any messy quote enclosure and data concatenation.
While languages have different ways to bind values to parameters, one way in MS Access is to use querydef parameters as demonstrated below.
Save your queries as stored objects with PARAMETERS clause (only compliant in MS Access SQL dialect). This helps abstract code from data.
Finally, properly use the update query syntax: UPDATE <table> SET <field>=<value> ...
Insert SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION])
VALUES (MEMBER_Param, OFFICE_Param, RANK_Param, OPTYPE_Param,
RLA_Param, MQT_PROGRAM_Param, MQT_POSITION_Param);
Update SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
UPDATE [ROSTER]
SET MEMBER = MEMBER_Param, OFFICE = OFFICE_Param, RANK = RANK_Param,
OPTYPE = OPTYPE_Param, RLA = RLA_Param, [MQT-PROGRAM] = MQT_PROGRAM_Param,
[MQT-POSITION] = MQT_POSITION_Param;
VBA (no SQL shown)
Dim mbrName As String, myquery As String, mymsg As String
Dim qdef As QueryDef
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
If Me.opgMngRoster.Value = 1 Then
myquery = "myRosterInsertQuery"
mymsg = "Added: " & mbrName
Else
myquery = "myRosterUpdateQuery"
mymsg = "Updated: " & mbrName
End If
' ASSIGN TO STORED QUERY
Set qdef = CurrentDb.QueryDefs(myquery)
' BIND PARAMS
qdef!MEMBER_Param = mbrName
qdef!OFFICE_Param = Me.cbxOffice.Value
qdef!RANK_Param = Me.cbxRank.Value
qdef!OPTYPE_Param = Me.cbxOpType
qdef!RLA_Param = Me.cbxRLA.Value
qdef!MQT_PROGRAM_Param = Me.cbxMQT.Value
qdef!MQT_POSITION_Param = Me.cbxTngPos.Value
qdef.Execute dbFailOnError
'-Confirmation Msg
MsgBox mymsg, vbInformation
Set qdef = Nothing

Object reference not set to a instance of an Object

I have a gridview that fills with data, and a view button which gives more details of the record choosen by the user. I cannot figure out why I am getting the error:
Object reference not set to a instance of an Object
I have narrowed it down to between my two message boxes. The First message box comes up but it crashes before the second. Any suggestions would be greatly appreciated.
Protected Sub CountAlerts_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles CountAlerts.RowCommand
If (e.CommandName = "Viewdtails") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim NDC, Unit, Cell, DTTM, prod, Query, _startdt, _enddt As String
Dim DS As DataSet
NDC = CountAlerts.DataKeys(index).Values("NDC")
Cell = CountAlerts.DataKeys(index).Values("Cell")
Unit = CountAlerts.DataKeys(index).Values("Unit")
DTTM = CountAlerts.DataKeys(index).Values("TimeDate")
prod = CountAlerts.DataKeys(index).Values("ProductDesc")
_startdt = If(StartDate.Text = "", DateAdd(DateInterval.Day, -7, System.DateTime.Now).ToShortDateString, StartDate.Text)
_enddt = If(EndDate.Text = "", System.DateTime.Now.ToShortDateString, EndDate.Text)
For Each irow As GridViewRow In CycleCountAlerts.Rows
If irow.Attributes("class") = "highlight" Then
irow.Attributes.Remove("class")
End If
Next
CountAlerts.Rows(index).Attributes("class") = "highlight"
Query = " EXEC [Audits].[dbo].[ExceptionDetailsCombined] '" & NDC & "', '" & Cell & "', '" & Unit & "', '" & DTTM & "', '" & Master.CF_User.Viewing & "' "
DS = SelectQuery(Query)
If (DS.Tables.Count > 0) Then
unitbox.Text = DS.Tables(0).Rows(0)("Unit")
cellbx.Text = DS.Tables(0).Rows(0)("Cell")
ndcbox.Text = DS.Tables(0).Rows(0)("NDC")
namebox.Text = DS.Tables(0).Rows(0)("ProductDesc")
cycdttmbx.Text = DS.Tables(0).Rows(0)("TimeDate")
cycusr.Text = DS.Tables(0).Rows(0)("CycUser")
todisp.Text = DS.Tables(0).Rows(0)("TODISPSIZE")
topkgbox.Text = DS.Tables(0).Rows(0)("TOPKGSIZE")
toqtybx.Text = DS.Tables(0).Rows(0)("TOQTY")
FRQTYbx.Text = DS.Tables(0).Rows(0)("FRQTY")
TextBox2.Text = DS.Tables(0).Rows(0)("ActualQTY")
cycvarqbox.Text = DS.Tables(0).Rows(0)("CYCLEVARQTY")
CycleVarPctbx.Text = DS.Tables(0).Rows(0)("CYCLEVARPCT")
alertrsnbx.Text = DS.Tables(0).Rows(0)("AlertReason")
combox.Text = DS.Tables(0).Rows(0)("AcceptComment")
acusr.Text = DS.Tables(0).Rows(0)("AcceptUser")
acctime.Text = DS.Tables(0).Rows(0)("AcceptTime")
accstatbx.Text = DS.Tables(0).Rows(0)("AcceptStatus")
displbl.Text = DS.Tables(0).Rows(0)("Disposition")
End If
Query = " EXEC [CF_Audits].[dbo].[CommentTrackerCombined] '" & Master.CF_User.EmployeeID & "', '" & NDC & "', '" & Cell & "', '" & Unit & "', '" & _startdt & "', '" & _enddt & "', '" & Master.CF_User.Viewing & "' "
DS = SelectQuery(Query)
If (DS.Tables.Count > 0) Then
ExceptionHist_GV.DataSource = DS
ExceptionHist_GV.DataBind()
ExceptionHist_GV.UseAccessibleHeader = True
MsgBox("except gv header") 'Runs up to here.
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
MsgBox("except gv header 2") ' Does not make it to here.
End If
End If
End Sub
Most likely TableRowSection or TableRowSection.TableHeader is/are Nothing
Check that these are initialised before using them
If MsgBox("except gv header")
If Not TableRowSection Is Nothing AndAlso Not TableRowSection.TableHeader Is Nothing Then
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
Else
MsgBox "How did we get here?"
End If
MsgBox("except gv header 2")
If you see the message "How did we get here" that indicates you have not initialised you object
In object orientated languages you need to instantiate an object before you can use it.
Something in this line:
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
has not been instantiated with the new keyword. You can find out exactly what by checking the details of the Exception which was thrown.
It will be either ExceptionHist_GV or TableRowSection.

Weird issue with saving to SQL database

I have managed to create a connection to the database and am able to save information to it from my form, the form contains 22 textboxes, a save and another exit button.
I have set the form to retrieve data in the form_load. I have used the "UPDATE" SQL command on the save button and it does save the data on all 22 textboxes (all textboxes are linked to their separate columns). But only one record will be needed that is why I did not use the "INSERT" command.
The problem arises when I click the save button, all (19) textboxes are saved but when I retrieve the text (by reloading the form), each of the 20, 21, 22 textboxes (only) the text of the 20th textbox keeps on moving tho the next textbox e.g. 20>21>22>20>21>22 is interchanged amongst themselves.
Please help me (I googled this but found nothing on this) and please tell me why this is happening.
The code is below:
Dim sqCon As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;Database=MegaDatabase;Integrated Security=SSPI")
Dim sqCmd As New SqlClient.SqlCommand
sqCmd.Connection = sqCon
Dim DatabaseErrorMsg As String = "Unable to save the details. Please contact the program developers."
Dim DatabaseErrorTitle As String = "Database Editing Error"
Dim DatabaseDoneSave As String = "New records made/updated successfully"
Dim CompNmtxtS As String
Dim TrdNmtxtS As String
Dim ComRegtxtS As String
Dim WTNmtxtS As String
Dim VRegtxtS As String
Dim TextBox1S As String
Dim ComPosttxtS As String
Dim StrAddrtxtS As String
Dim ComCitytxtS As String
Dim ComCounttxtS As String
Dim RegAddrtxtS As String
Dim ComZiptxtS As String
Dim RepTeltxtS As String
Dim ComFaxtxtS As String
Dim RepCelltxtS As String
Dim W_URLtxtS As String
Dim EWebtxtS As String
Dim BankNametxtS As String
Dim BankBranchtxtS As String
Dim BraCodetxtS As String
Dim BankAcctxtS As String
Dim TextBox2S As String
CompNmtxtS = CompNmtxt.Text
TrdNmtxtS = TrdNmtxt.Text
ComRegtxtS = ComRegtxt.Text
WTNmtxtS = WTNmtxt.Text
VRegtxtS = VRegtxt.Text
TextBox1S = TextBox1.Text
ComPosttxtS = ComPosttxt.Text
StrAddrtxtS = StrAddrtxt.Text
ComCitytxtS = ComCitytxt.Text
ComCounttxtS = ComCounttxt.Text
RegAddrtxtS = RegAddrtxt.Text
ComZiptxtS = ComZiptxt.Text
RepTeltxtS = RepTeltxt.Text
ComFaxtxtS = ComFaxtxt.Text
RepCelltxtS = RepCelltxt.Text
ComFaxtxtS = ComFaxtxt.Text
W_URLtxtS = W_URLtxt.Text
EWebtxtS = EWebtxt.Text
BankNametxtS = BankNametxt.Text
BankBranchtxtS = BankBranchtxt.Text
BraCodetxtS = BraCodetxt.Text
BankAcctxtS = BankAcctxt.Text
TextBox2S = TextBox2.Text
Try
'*NOTE: UPDATE function will only UPDATE the fields when there is already something in there, as it cannot work for the INSERT command
'Format for UPDATE command: USE DatabaseName; UPDATE Tablename SET ColumnName = '" & declared string name & "'"
sqCmd.CommandText = ("USE MegaDatabase; UPDATE CompDetails SET CompName = '" & CompNmtxtS & "', TradeName = '" & TrdNmtxtS & "', CompReg = '" & ComRegtxtS & "', WTnum = '" & WTNmtxtS & "', VATregNo = '" & VRegtxtS & "', TaxPeriod = '" & TextBox1S & "', CompPostalAddr = '" & ComPosttxtS & "', CompPhysAddr = '" & StrAddrtxtS & "', CompCity = '" & ComCitytxtS & "', CompCountry = '" & ComCounttxtS & "', CompProvince = '" & RegAddrtxtS & "', CompZip = '" & ComZiptxtS & "', CompTel = '" & RepTeltxtS & "', CompFax = '" & ComFaxtxtS & "', CompCell = '" & RepCelltxtS & "', CompWebsite = '" & W_URLtxtS & "', CompEmail = '" & EWebtxtS & "', CompBankName = '" & BankNametxtS & "', CompBranchName = '" & BankBranchtxtS & "', CurrentTaxTable = '" & TextBox2S & "', CompBranchCode = '" & BraCodetxtS & "', CompAccNo = '" & BankAcctxtS & "'")
sqCon.Open()
sqCmd.ExecuteNonQuery()
sqCon.Close()
Catch ex As Exception
MessageBox.Show(DatabaseErrorMsg, DatabaseErrorTitle, MessageBoxButtons.OK)
Finally
Me.Close()
frmMDImainform.MainMenuStrip.Enabled = True
MessageBox.Show(DatabaseDoneSave, "Done Saving...", MessageBoxButtons.OK)
End Try
For the loading part:
Try
sqCmd.CommandText = "SELECT TOP 1 [CompName],[TradeName],[CompReg],[WTnum],[VATregNo],[TaxPeriod],[CompPostalAddr],[CompPhysAddr],[CompCity],[CompCountry],[CompProvince],[CompZip],[CompTel],[CompFax],[CompCell],[CompWebsite],[CompEmail],[CompBankName],[CompBranchName],[CurrentTaxTable],[CompBranchCode],[CompAccNo] FROM [MegaDatabase].[dbo].[CompDetails]"
sqCon.Open()
sqRdr = sqCmd.ExecuteReader()
Catch ex As Exception
End Try
Do While sqRdr.Read() 'No need for VbTab and Vb crlf
CompNmtxt.Text = CompNmtxt.Text & sqRdr.GetValue(0)
TrdNmtxt.Text = TrdNmtxt.Text & sqRdr.GetValue(1)
ComRegtxt.Text = ComRegtxt.Text & sqRdr.GetValue(2)
WTNmtxt.Text = WTNmtxt.Text & sqRdr.GetValue(3)
VRegtxt.Text = VRegtxt.Text & sqRdr.GetValue(4)
TextBox1.Text = TextBox1.Text & sqRdr.GetValue(5)
ComPosttxt.Text = ComPosttxt.Text & sqRdr.GetValue(6)
StrAddrtxt.Text = StrAddrtxt.Text & sqRdr.GetValue(7)
ComCitytxt.Text = ComCitytxt.Text & sqRdr.GetValue(8)
ComCounttxt.Text = ComCounttxt.Text & sqRdr.GetValue(9)
RegAddrtxt.Text = RegAddrtxt.Text & sqRdr.GetValue(10)
ComZiptxt.Text = ComZiptxt.Text & sqRdr.GetValue(11)
RepTeltxt.Text = RepTeltxt.Text & sqRdr.GetValue(12)
ComFaxtxt.Text = ComFaxtxt.Text & sqRdr.GetValue(13)
RepCelltxt.Text = RepCelltxt.Text & sqRdr.GetValue(14)
W_URLtxt.Text = W_URLtxt.Text & sqRdr.GetValue(15)
EWebtxt.Text = EWebtxt.Text & sqRdr.GetValue(16)
BankNametxt.Text = BankNametxt.Text & sqRdr.GetValue(17)
BankBranchtxt.Text = BankBranchtxt.Text & sqRdr.GetValue(18)
BraCodetxt.Text = BraCodetxt.Text & sqRdr.GetValue(19)
BankAcctxt.Text = BankAcctxt.Text & sqRdr.GetValue(20)
TextBox2.Text = TextBox2.Text & sqRdr.GetValue(21)
Loop
Thanks for reading
You have a mixup in the order of your columns in your query vs. accessing the columns by index when reading your resultset:
In your query column #21 (last column, zero-based index) is [CompAccNo] but when reading you assign column #21 to TextBox2.Text.
I'd suggest you rather access your columns by name when reading:
CompNmtxt.Text = CompNmtxt.Text & sqRdr.GetValue("CompName")
TrdNmtxt.Text = TrdNmtxt.Text & sqRdr.GetValue("TradeName")
ComRegtxt.Text = ComRegtxt.Text & sqRdr.GetValue("CompReg")
'...
Another point: Get rid of creating your update query by concatenating user input - use Command Parameters instead!