"Object reference not set" error when creating a form - vb.net

I got this error when running my program. I wasn't like this before when I'm creating this program.
An error occurred creating the form.
See Exception.InnerException for details.
The error is:
Object reference not set to an instance of an object.
Here is the code in the form :
Imports System.Data
Imports System.Data.OleDb
Public Class IndexFrm
#Region "Connection"
Dim con As OleDbConnection
Dim scmd As OleDbCommand
Dim conreader As OleDbDataReader
Dim dbcon As String = Me.OpenFileDialog1.FileName & ";Jet Oledb:Database Password=*****"
#End Region
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
FrmSynoyms.Show()
FrmAntonyms.Hide()
FrmAnalogy.Hide()
FrmMath.Hide()
FrmAbstract.Hide()
FrmAbstract2.Hide()
FrmAbstract3.Hide()
FrmAbstract4.Hide()
StdntsFrm.Hide()
End Sub
Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
FrmAntonyms.Show()
FrmAnalogy.Hide()
FrmSynoyms.Hide()
FrmMath.Hide()
FrmAbstract.Hide()
FrmAbstract2.Hide()
FrmAbstract3.Hide()
FrmAbstract4.Hide()
StdntsFrm.Hide()
End Sub
Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
FrmAnalogy.Show()
FrmAntonyms.Hide()
FrmSynoyms.Hide()
FrmMath.Hide()
FrmAbstract.Hide()
FrmAbstract2.Hide()
FrmAbstract3.Hide()
FrmAbstract4.Hide()
StdntsFrm.Hide()
End Sub
Private Sub StudentsFormToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StudentsFormToolStripMenuItem1.Click
StdntsFrm.Show()
FrmAnalogy.Hide()
FrmAntonyms.Hide()
FrmSynoyms.Hide()
FrmMath.Hide()
FrmAbstract.Hide()
FrmAbstract2.Hide()
FrmAbstract3.Hide()
FrmAbstract4.Hide()
End Sub
Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton4.Click
FrmMath.Show()
FrmAnalogy.Hide()
FrmAntonyms.Hide()
FrmSynoyms.Hide()
FrmAbstract.Hide()
FrmAbstract2.Hide()
FrmAbstract3.Hide()
FrmAbstract4.Hide()
StdntsFrm.Hide()
End Sub
Private Sub ToolStripButton5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton5.Click
FrmAbstract.Show()
FrmAntonyms.Hide()
FrmAnalogy.Hide()
FrmMath.Hide()
StdntsFrm.Hide()
End Sub
'Private Sub IndexFrm_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
' If e.KeyCode = Keys.Escape Then
' Try
' If Me.WindowState = FormWindowState.Minimized Then
' Me.WindowState = FormWindowState.Minimized
' NotifyIcon1.Visible = True
' Me.Hide()
' End If
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
' End If
'End Sub
Private Sub IndexFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ToolStripButton1.Enabled = False
Me.ToolStripButton2.Enabled = False
Me.ToolStripButton3.Enabled = False
Me.ToolStripButton4.Enabled = False
Me.ToolStripButton5.Enabled = False
Me.StudentsFormToolStripMenuItem1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Label3.Text = Val(Me.Label3.Text) - 1
If Me.Label1.Text = "0" And Me.Label2.Text = "0" And Me.Label3.Text = "0" Then
Me.Timer1.Stop()
Me.Timer1.Enabled = False
MsgBox("TIME IS UP")
SynonymsSave()
AntonymsSave()
AnalogySave()
MathSave()
AbstractSave()
StdntsFrm.TxtStdntName.Clear()
StdntsFrm.TxtStdntsMI.Clear()
StdntsFrm.TxtStdntsLast.Clear()
StdntsFrm.TxtStdntAdd.Clear()
StdntsFrm.TxtStdntSchool.Clear()
StdntsFrm.TxtSchoolAdd.Clear()
StdntsFrm.TxtStdntAdv.Clear()
StdntsFrm.StdntTel.Clear()
StdntsFrm.Show()
Else
If Me.Label3.Text = "0" And Me.Label2.Text <> "0" Then
Me.Label3.Text = "59"
Me.Label2.Text = Val(Me.Label2.Text) - 1
ElseIf Me.Label2.Text = "0" And Me.Label1.Text <> "0" Then
Me.Label2.Text = "2"
Me.Label1.Text = Val(Me.Label1.Text) - 1
ElseIf Me.Label1.Text = "0" Then
Me.Label1.Text = "0"
ElseIf Me.Label2.Text = "0" And Me.Label1.Text = "0" Then
Me.Label2.Text = "0"
End If
End If
End Sub
Private Sub StudentsFormToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
FrmDBPath.Show()
End Sub
Private Sub IndexFrm_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
Try
If Me.WindowState = FormWindowState.Minimized Then
Me.WindowState = FormWindowState.Minimized
NotifyIcon1.Visible = True
Me.Hide()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
Try
Me.Show()
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OpenDatabaseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenDatabaseToolStripMenuItem.Click
Dim DBpath As String
With OpenFileDialog1
.AddExtension = True
.CheckPathExists = True
.DefaultExt = ".mdb"
.DereferenceLinks = True
.Filter = "Access File (*.mdb)|*.mdb|All files|*.*"
.Multiselect = False
.RestoreDirectory = True
.ShowHelp = True
.ShowReadOnly = True
.Title = "Select file to open"
.ValidateNames = True
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Try
DBpath = My.Computer.FileSystem.ReadAllText(.FileName)
Me.StudentsFormToolStripMenuItem1.Enabled = True
Catch ex As Exception
MsgBox("THE DATABASE IS ALREADY BEING USED", MsgBoxStyle.Exclamation)
End Try
End If
End With
End Sub
Sub SynonymsSave()
con = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;Data source=" & dbcon & ";Jet Oledb:Database Password=*****")
con.Open()
Dim qstring As String = "Insert into tblStdntsScores (StdntName,Synonyms,ScoreDate) values ('" & FrmSynoyms.Label59.Text & "','" & FrmSynoyms.Label58.Text & "','" & StdntsFrm.Label13.Text & "')"
scmd = New OleDbCommand(qstring, con)
scmd.ExecuteReader()
scmd.Dispose()
con.Close()
FrmSynoyms.HistorySave()
End Sub
Sub AntonymsSave()
con = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;Data source=" & dbcon & ";Jet Oledb:Database Password=*****")
con.Open()
Dim qstring As String = "Update tblStdntsScores set Antonyms='" & FrmAntonyms.Label28.Text & "' where StdntName='" & FrmAntonyms.Label29.Text & "'"
scmd = New OleDbCommand(qstring, con)
scmd.ExecuteReader()
scmd.Dispose()
con.Close()
FrmAntonyms.HistorySave()
End Sub
Sub AnalogySave()
con = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;Data source=" & dbcon & ";Jet Oledb:Database Password=*****")
con.Open()
Dim qstring As String = "Update tblStdntsScores set Analogy='" & FrmAnalogy.Label308.Text & "' where StdntName='" & FrmAnalogy.Label368.Text & "'"
scmd = New OleDbCommand(qstring, con)
scmd.ExecuteReader()
scmd.Dispose()
con.Close()
FrmAnalogy.HistorySave()
End Sub
Sub MathSave()
con = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;Data source=" & dbcon & ";Jet Oledb:Database Password=*****")
con.Open()
Dim qstring As String = "Update tblStdntsScores set Math='" & FrmMath.Label67.Text & "' where StdntName='" & FrmMath.Label68.Text & "'"
scmd = New OleDbCommand(qstring, con)
scmd.ExecuteReader()
scmd.Dispose()
con.Close()
FrmMath.HistorySave()
End Sub
Sub AbstractSave()
con = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;Data source=" & dbcon & ";Jet Oledb:Database Password=*****")
con.Open()
Dim qstring As String = "Update tblStdntsScores set Abstract='" & FrmAbstract4.Label36.Text & "' where StdntName='" & FrmAbstract.Label36.Text & "'"
scmd = New OleDbCommand(qstring, con)
scmd.ExecuteReader()
scmd.Dispose()
con.Close()
FrmAbstract4.HistorySave()
End Sub
End Class
Please help, guys.

Dim dbcon As String = Me.OpenFileDialog1.FileName & "...etc"
Here you are trying to initialize a string with a control property value. Class scoped variables (fields) are initialized before any other constructor code (ie: InitializeComponent()) is called, so here OpenFileDialog1 does not exist yet.

Related

Debugging in vb.net?

I'm new to coding, I've been working on my project of online billing system using Visual Basic.
The complete coding has been done, but while running the code, the totalitems and totalamt is not being calculated. Can you please debug or guide me how can I resolve this issue...
It shows errors like
1.conversion of type dbnull to string is not valid
2.string or binary data would be truncated.
Public Class billing
Dim disAmount As Double
Dim getProducID As Integer
Dim getStocks As Integer
Dim validatestock As Integer
Dim getUnitPrice As Double
Dim loadqty As Double
Dim discount As Boolean
Private Sub billing_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
getTransactionID()
GenerateInvoiceNo()
fillComboproduct()
End Sub
Private Sub getTransactionID()
Try
Dim trans As New Random
Dim numbers As Integer = trans.Next(1, 1000000)
Dim digitss As String = numbers.ToString("000000")
txttrans.Text = digitss
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub GenerateInvoiceNo()
lblInvoice.Text = "INV-" & GetUniqueKey(8)
End Sub
Public Shared Function GetUniqueKey(ByVal maxSize As Integer) As String
Dim chars As Char() = New Char(61) {}
chars = "123456789".ToCharArray()
Dim data As Byte() = New Byte(0) {}
Dim crypto As New RNGCryptoServiceProvider()
crypto.GetNonZeroBytes(data)
data = New Byte(maxSize - 1) {}
crypto.GetNonZeroBytes(data)
Dim result As New StringBuilder(maxSize)
For Each b As Byte In data
result.Append(chars(b Mod (chars.Length)))
Next
Return result.ToString()
End Function
Private Sub fillComboproduct()
Dim query As String = "Select productname From product order by productname"
Dim dtproduct As DataTable = getDataTable(query)
txtproductame.DataSource = dtproduct
txtproductame.DisplayMember = "productname"
' txtproductame.ValueMember = "productID"
If txtproductame.Items.Count > 0 Then
txtproductame.SelectedIndex = 0
End If
End Sub
Private Sub clear()
txtproductID.Text = ""
txtprice.Text = ""
txtQuantity.Text = ""
txtBalance.Text = ""
txttotal.Text = ""
txtAmtPaid.Text = ""
lblSubTotal.Text = "0"
txtproductame.Text = ""
lblTotalAmount.Text = "0.00"
lblSubTotal.Text = "0.00"
lblTotalItems.Text = "0"
txtprice.Text = ""
txtQuantity.Text = "1"
txttotal.Text = "0.00"
End Sub
Private Sub addbills()
Try
Sql = "INSERT INTO bills VALUES( '" & txtproductID.Text & "', '" & txtproductame.Text & "','" & txtQuantity.Text & "', '" & txtprice.Text & "','" & txttotal.Text & "', '" & lblInvoice.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub loadbills()
Try
Sql = "SELECT productID,productname,qty,unitprice FROM bills WHERE invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dgw.Rows.Clear()
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub totalamt()
Try
Sql = "SELECT sum(totalamt) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalAmount.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub gettotalitems()
Try
Sql = "SELECT sum(qty) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalItems.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub saveitems()
Try
Sql = "INSERT INTO transactionDetails VALUES('" & txttrans.Text & "','" & lblInvoice.Text & "', '" & lblTotalItems.Text & "', '" & lblTotalAmount.Text & "', '" & txtAmtPaid.Text & "','" & txtBalance.Text & "', '" & cmdpayment.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Billing Details Successfully saved", MsgBoxStyle.Information, "Saves Billing Details")
Else
MsgBox("Failed in Saves Billing Details", MsgBoxStyle.Information, "Saves Billing Details")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub txtproductame_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtproductame.SelectedIndexChanged
Try
ConnDB()
Dim da As New SqlDataAdapter(("select * from product where productname ='" & Trim(txtproductame.Text) & "'"), conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
Me.txtprice.Text = dt.Rows(0).Item("unitprice") & ""
Me.txtproductID.Text = dt.Rows(0).Item("productID") & ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub txtQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuantity.TextChanged
txttotal.Text = Val(txtQuantity.Text) * Val(txtprice.Text)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
getTransactionID()
GenerateInvoiceNo()
End Sub
Private Sub BindToText()
Try
With dgw
lblSubTotal.Text = Val(.SelectedRows(0).Cells("qty").Value) * Val(.SelectedRows(0).Cells("price").Value)
.SelectedRows(0).Cells("amt").Value = lblSubTotal.Text
End With
Catch ex As Exception
End Try
End Sub
Private Sub dgw_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgw.CellClick
BindToText()
End Sub
Private Sub dgw_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgw.SelectionChanged
BindToText()
End Sub
Private Sub txtAmtPaid_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmtPaid.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
Try
txttotal.Text = Val(txtprice.Text) * Val(txtQuantity.Text)
If txtproductame.Text = "" Or txtQuantity.Text = "" Then
MsgBox("Please enter a product Or Quantity before you click load button")
Else
addbills()
loadbills()
totalamt()
gettotalitems()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
txttotal.Text = ""
txtQuantity.Text = ""
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
If dgw.Rows.Count = 0 Then
MsgBox("Please load drugs in the cart before saving", MsgBoxStyle.Exclamation, "Validation")
Exit Sub
End If
If txtAmtPaid.Text = "" Then
MsgBox("Please fill-in Amount Paid by Customer", MsgBoxStyle.Information, "Validation")
txtAmtPaid.Focus()
Exit Sub
ElseIf cmdpayment.Text = "" Then
MsgBox("Please choose Payment status field", MsgBoxStyle.Information, "Validation")
cmdpayment.Focus()
Exit Sub
End If
saveitems()
'DecreaseStocksOnhand()
'UpdateToDecreaseStocksOnHand()
btnreceipt.Show()
getTransactionID()
' GenerateInvoiceNo()
dgw.Rows.Clear()
' btnreceipt.Show()
End Sub
Private Sub Deleteitem()
Try
Sql = "DELETE * FROM bills WHERE productID = '" & dgw.SelectedRows(0).Cells("productID").Value & "'"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnremove.Click
If MsgBox("Are you sure you want to remove this Product from Cart", MsgBoxStyle.YesNo, "Validation") = MsgBoxResult.Yes Then
Deleteitem()
loadbills()
gettotalitems()
totalamt()
clear()
txttotal.Text = ""
txtQuantity.Text = ""
End If
End Sub
Private Sub txtAmtPaid_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmtPaid.TextChanged
txtBalance.Text = Val(lblTotalAmount.Text) - Val(txtAmtPaid.Text)
End Sub
Private Sub cmdpayment_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdpayment.SelectedIndexChanged
If cmdpayment.SelectedIndex = 1 Then
txtAmtPaid.Text = "0"
End If
End Sub
Private Sub btnreceipt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreceipt.Click
receipt.lblInvoice.Text = lblInvoice.Text
receipt.Show()
End Sub
End Class

Copy System.Data.Datatable to Access DB Programmatically Vb.net [duplicate]

Can someone please explain why, when I click the "Commit" button, I get the error
Syntax error in INSERT INTO statement.
Here's the code.
Public Class Form3
Dim inc As Integer
Dim MaxRows As Integer
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = D:\TA_Officers.mdb"
con.Open()
sql = "SELECT * from TA_OFFICER"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "TA_Officers")
con.Close()
MaxRows = ds.Tables("TA_Officers").Rows.Count
inc = -1
End Sub
Private Sub NavigateRecords()
txtFName.Text = ds.Tables("TA_Officers").Rows(inc).Item(1)
txtMInitial.Text = ds.Tables("TA_Officers").Rows(inc).Item(2)
txtLName.Text = ds.Tables("TA_Officers").Rows(inc).Item(3)
txtContact.Text = ds.Tables("TA_Officers").Rows(inc).Item(4)
txtEmail.Text = ds.Tables("TA_Officers").Rows(inc).Item(5)
txtPosition.Text = ds.Tables("TA_Officers").Rows(inc).Item(6)
txtCourse.Text = ds.Tables("TA_Officers").Rows(inc).Item(7)
txtAddress.Text = ds.Tables("TA_Officers").Rows(inc).Item(8)
End Sub
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
BtnCommit.Enabled = True
BtnAdd.Enabled = False
BtnUpdate.Enabled = False
BtnDel.Enabled = False
txtPosition.Clear()
txtLName.Clear()
txtFName.Clear()
txtMInitial.Clear()
txtAddress.Clear()
txtCourse.Clear()
txtEmail.Clear()
txtContact.Clear()
End Sub
Private Sub RdMember_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RdMember.CheckedChanged
Label2.Visible = False
txtPosition.Visible = False
End Sub
Private Sub RdOfficer_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RdOfficer.CheckedChanged
Label2.Visible = True
txtPosition.Visible = True
End Sub
Private Sub BtnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnUpdate.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("TA_Officers").Rows(inc).Item(1) = txtFName.Text
ds.Tables("TA_Officers").Rows(inc).Item(2) = txtMInitial.Text
ds.Tables("TA_Officers").Rows(inc).Item(3) = txtLName.Text
ds.Tables("TA_Officers").Rows(inc).Item(4) = txtContact.Text
ds.Tables("TA_Officers").Rows(inc).Item(5) = txtEmail.Text
ds.Tables("TA_Officers").Rows(inc).Item(6) = txtPosition.Text
ds.Tables("TA_Officers").Rows(inc).Item(7) = txtCourse.Text
ds.Tables("TA_Officers").Rows(inc).Item(8) = txtAddress.Text
da.Update(ds, "TA_Officers")
MsgBox("Data Updated!")
End Sub
Private Sub BtnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDel.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("TA_Officers").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
NavigateRecords()
da.Update(ds, "TA_Officers")
End Sub
Private Sub BtnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClear.Click
BtnCommit.Enabled = False
BtnAdd.Enabled = True
BtnUpdate.Enabled = True
BtnDel.Enabled = True
inc = 0
NavigateRecords()
End Sub
Private Sub BtnCommit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCommit.Click
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("TA_Officers").NewRow()
dsNewRow.Item("Firstname") = txtFName.Text
dsNewRow.Item("Middleinitial") = txtMInitial.Text
dsNewRow.Item("Lastname") = txtLName.Text
dsNewRow.Item("Mobilenumber") = txtContact.Text
dsNewRow.Item("Emailaddress") = txtEmail.Text
dsNewRow.Item("Position") = TxtPosition.Text
dsNewRow.Item("Course") = txtCourse.Text
dsNewRow.Item("Address") = txtAddress.Text
ds.Tables("TA_Officers").Rows.Add(dsNewRow)
**da.Update(ds, "TA_Officers")**
MsgBox("New Record added to the Database")
BtnCommit.Enabled = False
BtnAdd.Enabled = True
BtnUpdate.Enabled = True
BtnDel.Enabled = True
End If
End Sub
Private Sub BtnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBack.Click
Form2.Show()
Me.Close()
End Sub
Private Sub TA_MEMBERSBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.TA_MEMBERSBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TA_OfficersDataSet)
End Sub
End Class
Position is a reserved word for JET 4.0 - try to rename the column something else such as prog_position. Access will often let you create the column with a reserved name, but when you go to access it in code JET blocks it and gives you a generic Syntax error in INSERT INTO Statement error without being specific. Check out http://support.microsoft.com/kb/248738 for more information on reserved words. It is goods practice to always prefix your column names with something short so that you never run into conflicts or reserved word issues.
As Makita mentions, your problem stems from the fact that Position is a reserved word in Jet/ACE SQL. The solution is to add the following two lines of code after you create the OleDbCommandBuilder object:
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will tell the OleDbCommandBuilder to generate SQL statements like this
INSERT INTO [TA_OFFICER] ([FirstName], ...
...instead of
INSERT INTO TA_OFFICER (FirstName, ...
Wrapping the Position column name in those square brackets will tell the Jet database engine that it is a column name, not a keyword.
This kind of error can happen when you have different data type in the code and in the DB.
Checking the log can give some light on this.

unhandled exception of type system.data.sqlclient.sqlexception occurred in system.dll

I been having this error
"unhandled exception of type system.data.sqlclient.sqlexception occurred in system.dll
i cant seem to find what im missing and it points on my
Private Sub Check_Info()
etc..
etc...
etc.
dDA.FILL(dDS) '<<
Notes:
I have my SQLserver running and tables running their connections are ok.
Code below
#Region " Variable Declarations "
Public sConn As SqlConnection
Dim eDS As DataSet = New DataSet
Dim eDA As SqlDataAdapter = New SqlDataAdapter
Dim eDR As DataRow
Dim dDS As DataSet = New DataSet
Dim dDA As SqlDataAdapter = New SqlDataAdapter
Dim dDR As DataRow
'Public bExitApplication As Boolean
#End Region
#Region " User-defined Procedures "
Private Sub Check_Info()
sConn.Open()
eDA.SelectCommand = New SqlCommand("SELECT emp_fname,emp_lname,emp_mname FROM tblEmployee WHERE emp_idno='" & TextBox1.Text.ToString & "' and emp_pass='" & TextBox2.Text & "'", sConn)
eDS.Clear()
eDA.Fill(eDS)
If eDS.Tables(0).Rows.Count > 0 Then
eDR = eDS.Tables(0).Rows(0)
TextBox3.Text = eDR("emp_lname") & ", " & eDR("emp_fname") & " " & eDR("emp_mname")
dDA.SelectCommand = New SqlCommand("SELECT * FROM tblDTR WHERE emp_idno='" & TextBox1.Text & "' AND date_timein=#" & Format(Now, "MM/d/yyyy") & "# AND time_timeout IS NULL", sConn)
dDS.Clear()
dDA.Fill(dDS)
If dDS.Tables(0).Rows.Count > 0 Then
dDR = dDS.Tables(0).Rows(0)
Button1.Enabled = True
Button1.Text = "&Time Out"
TextBox4.Text = Format(dDR("time_timein"), "h:mm:ss tt")
Else
Button1.Enabled = True
Button1.Text = "&Time In"
End If
dDR = Nothing
dDS.Dispose()
dDA.Dispose()
Else
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
Button1.Enabled = False
End If
eDR = Nothing
eDS.Dispose()
eDA.Dispose()
sConn.Close()
End Sub
Private Sub ReturnFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox3.GotFocus, TextBox4.GotFocus, TextBox5.GotFocus
TextBox1.Focus()
End Sub
Private Sub TextboxChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
If (TextBox1.Text <> "" And TextBox2.Text <> "") Then
Check_Info()
End If
End Sub
Private Sub LoginGotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
End Sub
#End Region
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sConn = New SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=StudInfo;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")
Label2.Text = Format(Now, "MMMM d, yyyy h:mm:ss tt")
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label2.Text = Format(Now, "MMMM d, yyyy h:mm:ss tt")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Time-in and Time-out button
Dim strSQL As String
sConn.Open()
If Button1.Text = "&Time In" Then
dDR = dDS.Tables(0).NewRow()
TextBox4.Text = Format(Now, "h:mm:ss tt")
strSQL = "INSERT INTO tblDTR (emp_idno, date_timein, time_timein) VALUES ('" & TextBox1.Text & "', #" & Format(Now, "MM/d/yyyy") & "#, #" & TextBox4.Text & "#)"
Button1.Text = "&Time Out"
Else
TextBox5.Text = Format(Now, "h:mm:ss tt")
strSQL = "UPDATE tblDTR SET time_timeout=#" & TextBox5.Text & "# WHERE emp_idno='" & TextBox1.Text & "' AND date_timein=#" & Format(Now, "MM/d/yyyy") & "# and time_timein=#" & TextBox4.Text & "#"
Button1.Text = "&Time In"
End If
Dim dCmd As SqlCommand = New SqlCommand(strSQL, sConn)
dCmd.ExecuteNonQuery()
dCmd.Dispose()
dDR = Nothing
dDS.Dispose()
dDA.Dispose()
sConn.Close()
Button1.Enabled = False
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' clear the form
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
Button1.Text = "&Time In"
Button1.Enabled = False
TextBox1.Focus()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' System Administration
bExitApplication = True
Dim f As Form
f = New UserLogin
Me.Close()
f.Show()
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not bExitApplication Then
MsgBox("You cannot close the system this way..." & vbCrLf & vbCrLf & "Please Quit the application in the System Administration Module or by clicking Exit in the bottom of this window.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error: No Administrative Privilage")
e.Cancel = True
End If
End Sub
Private Sub Label7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label7.Click
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
MsgBox("Thank you for using Attandance Monitoring System")
bExitApplication = True
Application.Exit()
End Sub
End Class
almost certainly comes from this:
...date_timein=#" & Format(Now, "MM/d/yyyy") & "#...
you aren't generating VB code, you are generated SQL code, so don't use a # in a string literal. The proper way is to put in a parameter:
dDA.SelectCommand = New SqlCommand("SELECT * FROM tblDTR WHERE emp_idno=#EmpID AND date_timein=#Today AND time_timeout IS NULL", sConn)
cmd.Parameters.Add("#Today",DbType.DateTime).Value = DateTime.Now
cmd.Parameters.Add("#EmpID",DbType.Int).Value = TextBox1.Text

syntax error in insert into statement in vb.net back end of access

i have created a mail tracker having a backend on ms-access 97-2003 format and all the code is fine except getting error on the said above please help on resolving the issue please refer to the screen shot and i'll provide the code below it
Imports System.Data.OleDb
Public Class Form1
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Application.StartupPath & "\fsl.mdb;Persist Security Info=False;"
Dim cnn As OleDb.OleDbConnection
Dim now As Date = System.DateTime.Now()
Dim mydate As Date = now
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles quit.Click
Me.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.cnn = New OleDb.OleDbConnection
rdate.Clear()
sdate.Clear()
orgi.Clear()
esub.Clear()
mno.Clear()
comap.Clear()
srno.Clear()
actby.Clear()
remark.Clear()
tim.Clear()
Label11.Visible = False
srno.Visible = False
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
cnn.ConnectionString = dbprovider
cnn.Open()
Me.sdate.Text = now
Me.tim.Text = now
Dim sqlquery As String = "Insert into fsl([rdate],[sdate],[Originator],[Circ],[Subject],[Mno],[Comp],[Type],[subtype],[actby],[srno],[Status],[Agent],[remarks],[Tim])values (#rdate,#sdate,#Originator,#Circ,#Subject,#Mno,#Comp,#Type,#subtype,#actby,#srno,#Status,#Agent,#remarks,#Tim)"
Dim cmd As OleDbCommand = New OleDbCommand(sqlquery, cnn)
cmd.Parameters.AddWithValue("#rdate", Me.rdate.Text)
cmd.Parameters.AddWithValue("#sdate", Me.sdate.Text)
cmd.Parameters.AddWithValue("#originator", Me.orgi.Text)
cmd.Parameters.AddWithValue("#circ", Me.circ.Text)
cmd.Parameters.AddWithValue("#subject", Me.esub.Text)
cmd.Parameters.AddWithValue("#mno", Me.mno.Text)
cmd.Parameters.AddWithValue("#comp", Me.comap.Text)
cmd.Parameters.AddWithValue("#type", Me.type.Text)
cmd.Parameters.AddWithValue("#subtype", Me.subty.Text)
cmd.Parameters.AddWithValue("#actby", Me.actby.Text)
cmd.Parameters.AddWithValue("#srno", Me.srno.Text)
cmd.Parameters.AddWithValue("#status", Me.status.Text)
cmd.Parameters.AddWithValue("#agent", Me.agent.Text)
cmd.Parameters.AddWithValue("#remarks", Me.remark.Text)
cmd.Parameters.AddWithValue("#tim", Me.tim.Text)
cmd.ExecuteNonQuery()
cnn.Close()
MsgBox("Record Added Successfully")
rdate.Clear()
sdate.Clear()
orgi.Clear()
esub.Clear()
mno.Clear()
comap.Clear()
srno.Clear()
actby.Clear()
remark.Clear()
tim.Clear()
End Sub
Private Sub type_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles type.LostFocus
If type.SelectedItem = "E-Bridge" Then
Label11.Visible = True
srno.Visible = True
Else
Label11.Visible = False
srno.Visible = False
End If
End Sub
Private Sub subty_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles subty.LostFocus
If subty.SelectedItem = "E-Bridge" Then
Label11.Visible = True
srno.Visible = True
ElseIf subty.SelectedItem = "Churn" Then
Label11.Visible = True
srno.Visible = True
Else
Label11.Visible = False
srno.Visible = False
End If
End Sub
End Class
You are missing the "VALUES" keyword.
Dim sqlquery As String = "Insert into fsl Values ([rdate],[sdate], ...
Take a look at this website:
http://www.w3schools.com/sql/sql_insert.asp

Why is my form disappearing when I press ENTER?

Good-day,
I'm experiencing a very strange event that just started happening. Whenever I press the ENTER button on my keyboard, I expect the KeyDown event of my textbox to be raised and the corresponding code run. Instead, the form disappears (as if the .Hide() method has been called). When I debug, I see that the code that's supposed to run after the KeyDown event is raised is executing accordingly - but the form just disappears.
I've never encountered this before, so I don't know what to do. Any help would be appreciated. Thanks.
HERE'S THE CODE OF MY FORM:
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class FormAdd
#Region "VARIABLE DECLARATIONS CODE"
'FOR MySQL DATABASE USE
Public dbConn As MySqlConnection
'FOR CARD NUMBER FORMATTING
Private CF As New CardFormatter
'FOR CARD ENCRYPTION
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encryptedCard As String
#End Region
#Region "SUB-ROUTINES AND FUNCTIONS"
Private Sub GetDBdata()
Try
If TextBoxAccount.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxAccount.Focus()
Else
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
If dbTable.Rows.Count > 0 Then
'MessageBox.Show("Customer Account Found!")
Call recordFound()
TextBoxLastName.Text = dbTable.Rows(0).Item("nameLAST")
TextBoxFirstName.Text = dbTable.Rows(0).Item("nameFIRST")
TextBoxSalutation.Text = dbTable.Rows(0).Item("nameSALUTATION")
TextBoxCompanyName.Text = dbTable.Rows(0).Item("nameCOMPANY")
Else
'MessageBox.Show("No Customer Records Found! Please try again!")
Call recordNotFound()
ButtonReset.PerformClick()
End If
dbConn.Close()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub SetDBData()
Try
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim noCard As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM cc_master WHERE ccNumber = '" & TextBoxCard.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows() = True Then
MessageBox.Show("This Credit/Debit Card Already Exists! Try Another!")
noCard = False
Else
noCard = True
End If
End While
dbData.Close()
If noCard = True Then
'PERFORM CARD ENCRYPTION
'PERFORM DATABASE SUBMISSION
Dim dbQuery2 As String = "INSERT INTO cc_master (ccType, ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, customer_accountNumber)" & _
"VALUES('" & ComboBoxCardType.SelectedItem & "','" & TextBoxCard.Text & "','" & TextBoxExpireMonth.Text & "','" & TextBoxExpireYear.Text & _
"','" & TextBoxZipCode.Text & "','" & TextBoxCVV2.Text & "','" & Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & TextBoxAccount.Text & "');"
Dim dbData2 As MySqlDataReader
Dim dbAdapter2 As New MySqlDataAdapter
Dim dbCmd2 As New MySqlCommand
dbCmd2.CommandText = dbQuery2
dbCmd2.Connection = dbConn
dbAdapter2.SelectCommand = dbCmd2
dbData2 = dbCmd2.ExecuteReader
MessageBox.Show("Credit/Debit Card Information Saved SUCCESSFULLY!")
ButtonReset.PerformClick()
End If
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub ResetForm()
TextBoxAccount.Clear()
TextBoxLastName.Clear()
TextBoxFirstName.Clear()
TextBoxSalutation.Clear()
TextBoxCard.Clear()
ComboBoxCardType.SelectedItem = ""
TextBoxCompanyName.Clear()
TextBoxCVV2.Clear()
TextBoxExpireMonth.Clear()
TextBoxExpireYear.Clear()
TextBoxZipCode.Clear()
CheckBoxConfirm.Checked = False
TextBoxAccount.SelectionStart = 0
TextBoxAccount.SelectionLength = Len(TextBoxAccount.Text)
TextBoxAccount.Focus()
GroupBoxInputError.Hide()
LabelInstruction.Show()
GroupBox1.Height = 75
End Sub
Private Sub recordFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Green
LabelError.ForeColor = Color.White
LabelError.Text = "RECORD FOUND!"
GroupBoxInputError.Visible = True
GroupBox1.Height = 345
ButtonReset.Show()
LabelInstruction.Hide()
ComboBoxCardType.Focus()
End Sub
Private Sub recordNotFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Red
LabelError.ForeColor = Color.White
LabelError.Text = "NO RECORD FOUND!"
GroupBoxInputError.Visible = True
End Sub
'Public Sub encryptCard()
' Try
' DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
' DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
' Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxCard.Text)
' TextBoxCard.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
' Catch ex As Exception
' MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "TOOLSTRIP MENU CONTROL CODE"
Private Sub ExitAltF4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitAltF4ToolStripMenuItem.Click
End
End Sub
#End Region
#Region "BUTTON CONTROLS CODE"
Private Sub ButtonExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExit.Click
FormMain.Show()
Me.Close()
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
Call ResetForm()
End Sub
Private Sub ButtonSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click
Call SetDBData()
Call ResetForm()
End Sub
Private Sub ButtonEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles ButtonEncrypt.Click
End Sub
#End Region
#Region "FORM CONTROLS CODE"
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
TextBoxAccount.Focus()
Me.KeyPreview = True
Timer1.Enabled = True
Timer1.Interval = 1
GroupBoxInputError.Hide()
ButtonSubmit.Hide()
ButtonReset.Hide()
GroupBox1.Height = 75
'LabelFooter.Text = "Welcome " & FormLogin.TextBoxUsername.Text() & " | Timestamp: " & Date.Now.ToString
Try
LabelIP.Text = "IP: " & Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString
Catch ex As Exception
End Try
'Populate the Card Type combobox with the list of card types from the CardFormatter class
ComboBoxCardType.Items.AddRange(CF.GetCardNames.ToArray)
End Sub
#End Region
#Region "TEXTBOX CONTROLS CODE"
Private Sub TextBoxCard_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.GotFocus
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
Me.Refresh()
End Sub
Private Sub TextBoxCard_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.LostFocus
'//CARD VALIDATION//
' This code will check whether the card is a valid number or not. It doesn't check to see if the card is active.
' The code calls on the creditcard function stored in MyModules.vb
Try
If creditcard(TextBoxCard.Text) Then
'MsgBox("Card is Valid")
TextBoxCard.BackColor = Color.GreenYellow
TextBoxCard.ForeColor = Color.Black
GroupBoxInputError.Visible = False
TextBoxCard.Text = CF.GetFormattedString(ComboBoxCardType.Text, TextBoxCard.Text)
Me.Refresh()
Else
BWErrorNotice.RunWorkerAsync()
'MsgBox("Invalid Card")
GroupBoxInputError.Visible = True
TextBoxCard.Focus()
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBoxAccount_GotFocus(sender As Object, e As System.EventArgs) Handles TextBoxAccount.GotFocus
TextBoxAccount.SelectAll()
End Sub
Private Sub TextBoxAccount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAccount.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
If TextBoxAccount.Text <> "" Then
Call GetDBdata()
Else
MsgBox("You must enter an account number!", MsgBoxStyle.Exclamation, "ATTENTION PLEASE!")
TextBoxAccount.Focus()
End If
End If
'If e.KeyCode = Keys.Enter Then
' e.Handled = True
' SendKeys.Send("{Tab}")
'End If
End Sub
Private Sub TextBoxCard_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBoxCard.MouseClick
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End Sub
#End Region
#Region "OTHER/MISCELLANEOUS CONTROLS CODE"
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LabelDateTime.Text = DateTime.Now
End Sub
Private Sub BWErrorNotice_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWErrorNotice.DoWork
Do While Not creditcard(TextBoxCard.Text)
LabelError.BackColor = Color.Black
System.Threading.Thread.Sleep(500)
LabelError.BackColor = Color.Red
System.Threading.Thread.Sleep(500)
Loop
BWErrorNotice.CancelAsync()
End Sub
Private Sub CheckBoxConfirm_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxConfirm.CheckedChanged
If CheckBoxConfirm.Checked = True Then
ButtonSubmit.Show()
Else
ButtonSubmit.Hide()
End If
End Sub
#End Region
End Class
Although what follows will not likely solve the form disappearance problem, it will resolve a downstream issue:
In GetDBData(), you are assigning accountNumber to the value of TextBoxAcount.Text, which must be enclosed with quotes unless you employ a parameter which I strongly recommend you get in the habit of doing.
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Parameters offer a number of benefits including implicit type conversions, injection attack prevention, and will sometimes even cure unexpected behaviors.
I figured out the problem. I was calling Dispose() at the end of my GetDBData() function - so the form was getting disposed before execution returned back to the TextBox. I deleted it and all is well again.