Object reference not set to a instance of an Object - vb.net

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.

Related

VBA/Access: How to stop "You... FORM to be active window"

I want to be able to tell IF a form is the active window.
It seems simply invoking that method produces an error. I guess I could catch that error and run with it, but it's a backwards way of doing it.
Screen.ActiveForm.Name
This needs a form to be active. If I am breaking any rules of stackOverflow please be kind and remind me as I am new to forum.
Screen.parent, screen.activeControl, etc. What if VBA editor is open, as often it is?
Function CStatus(strStatus, ByRef intType As Integer, Optional ByRef erNo, Optional erMsg, Optional strDatum)
'pXname = "CStatus"
'pXStack = Left(pXStack, 500) & ">" & pXname
'Updates and manages the status bar
Dim strPreamble As String, strOut As String, strForm As String, strComment As String, strSQL As String, strPxStack As String, strCErrStack As String
Dim intColor As Double
Dim intPreLen As Integer
'On Error GoTo err_hand
'Color Codes
'12632256 = Lt Grey
'33023 = Orange
'65280 = Green
'16744576 = Steel Grey
'Define "Constants"
intPreLen = 350 'Length of previous message cache
'** Fix missings
If (IsMissing(strDatum) = True) Then strDatum = "[N/A]"
'** Other inits
strWindow = Screen.Parent.Name
strForm = Screen.ActiveForm.Name
'** intDebug ' Minimum Level of to report to status
'bEcho = True 'Whether to echo to status
intColor = errNoColor(intType)
'Error-level idiot explanations
strComment = "0"
If IsMissing(erNo) Then erNo = 0
If (IsNull(erMsg) = False) Then
If IsMissing(erMsg) = False Then strComment = erMsg
End If
strComment = errorTree(erNo)
strPreamble = Left(strPreamble, intPreLen) & "..."
strErrStack = Left(strErrStack, intPreLen) & " > " & pXname & ":" & intType
strCErrStack = strErrStack
reS:
If ((strForm = "finvmain") Or (strForm = "fclips")) Then Screen.ActiveForm.timeStatusUpdated = Now() 'Small field keeps time
If bEcho = True Then
strPxStack = ""
strCErrStack = "" 'Internal error stack
End If
strOut = Now() & " " & intType & " (" & strType & "): " & erNo & " " & strCErrStack & " >> " & strComment & " / " & strStatus & " [" & strDatum & "] .. " & strPreamble
If bEcho = True Then
If (strForm = "fInvMain") Then Screen.ActiveForm.txtStatus2 = Screen.ActiveForm.txtStatus 'Added second window to show previous message
Screen.ActiveForm.txtStatus = strOut
End If
Screen.ActiveForm.txtStatus.ForeColor = intColor
If strForm = "fInvMain" Then strTag = Screen.ActiveForm.Controls("txttag").value
'***Event Log
If erNo = "" Then erNo = 0
If IsMissing(erMsg) = True Then erMsg = ""
If IsMissing(strDatum) = True Then strDatum = ""
If Len(strPreamble) < 2 Then strPreamble = "[None]"
'Fixxed - Syntax Error for Some Odd Reason! Apr 27th
If ((strTag = Empty) And (strForm = "fInvMain")) Then strTag = Screen.ActiveForm.txtTag 'Attempt to add tag# to entry
strStatus = cleanString(strStatus)
strDatum = cleanString(strDatum)
strComment = cleanString(strComment)
strSQL = "INSERT INTO tEvents(txtdate, myerrno, interrno, myerrmsg, interrmsg, txtform, stack, process, Datum, idLink) VALUES ('" & Now() & "','" & intType & "','" & erNo & "','" & strStatus & "','" & strComment & "','" & strForm & "','" & strErrStack & "','" & pXname & "','" & strDatum & "','" & strTag & "');"
CurrentDb.Execute strSQL, dbFailOnError
Exit Function
err_hand:
If Err.Number = 2475 Then
bEcho = False
Resume reS
Else: MsgBox "555: CStatus Internal Error, Turn off error handling to view"
End If
End Function
I need a boolean true or false IF form is active. If it isn't, I can't put stuff into a textbox in that.
To determine if a particular form is open then set focus to form:
If CurrentProject.AllForms("finvmain").IsLoaded
strForm = "finvmain"
Elseif CurrentProject.AllForms("fclips").IsLoaded Then
strForm = "fclips"
End If
If strForm <> "" Then DoCmd.SelectObject acForm, strForm

Access VBA DLookup Multiple Critiera based on Variables

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 & "#")

Can't Update Values In Microsoft Access

I have a problem that when I try updating data the the program doesn't save it in the database.
This is the current code:
Dim y As Byte = Convert.ToByte(lblID.Text) - 1
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("dset").Rows(y).Item(1) = txtname.Text
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Else
MdAlertBox1.Text = "Please Select A Class The Class Box"
MdAlertBox1.Visible = True
End If
MdAlertBox1.Text = "Data Sucessfully Updated !"
MdAlertBox1.kind = MDAlertBox._Kind.Success
MdAlertBox1.Visible = True
getinfo.Start()
updatedata.Stop()
And the declared variables:
Dim conn As New OleDb.OleDbConnection
Dim DbProv As String = "PROVIDER=microsoft.ACE.OLEDB.12.0;"
Dim Src As String = " data source = c:\users\kingo\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\BigGymDB.accdb"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Put a debug.print to see the values you are passing to the Database. Like this:
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
'your code ---^
debug.print txtname.Text; txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text;
debug.print txtnotes.Text; txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
'your code ---v
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Then in two lines in the Immdiate Window, you should see whether these txtsub.Text and the other 3 inputs actually have something.

vbnet multiple combobox fill with one dataset

i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub

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!