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.
Related
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
I made a program Reminder System that Auto send email when the date i set in my apps much the date in my computer. the problem is i need to restart my apps so that the reminder will show or the form will be loaded. if not it will not alert. so i need your help guys if the date change in my computer my apps will auto reload or refresh so that if have reminders it will be send to email. btw my program will be installed in a server that will always be open so i just need to auto reload my form every time the date change. below is my code in setting the reminders.
Imports System.IO
Public Class Reminder
Dim m As MsgBoxResult
Dim t As String
Private Sub Reminder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = TimeOfDay.ToString("h:mm:ss tt")
Dim m1 As MsgBoxResult
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
If Date.Today = MonthCalendar1.TodayDate And File.Exists(t & ".txt") = True Then
m1 = MsgBox("You set a reminders for today. Would you like to send to EMAIL ?", MsgBoxStyle.YesNo)
If m1 = MsgBoxResult.Yes Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
Notetxt.Text = File.ReadAllText(t & ".txt")
sendEmail.Show()
sendEmail.emailtxt.Text = Notetxt.Text
sendEmail.Hide()
MsgBox("SEND EMAIL SUCCESSFUL", vbOKOnly)
lblMessage.Hide()
End If
End If
End Sub
Private Sub MonthCalendar1_DateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles MonthCalendar1.DateChanged
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
Try
If File.Exists(t & ".txt") = True Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Notetxt.Text = File.ReadAllText(t & ".txt")
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
lblMessage.Hide()
Else
m = MsgBox("Would you like to enter a reminders for this date?", MsgBoxStyle.YesNo)
If m = MsgBoxResult.Yes Then
MonthCalendar1.Enabled = False
MonthCalendar1.Hide()
Notetxt.Enabled = True
Notetxt.Show()
Notetxt.Text = ""
SaveBtn.Enabled = True
SaveBtn.Show()
Backbtn.Enabled = True
Backbtn.Show()
Addbtn.Enabled = True
Addbtn.Show()
delbtn.Enabled = True
delbtn.Show()
lblMessage.Hide()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Backbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Backbtn.Click
Notetxt.Enabled = False
Notetxt.Hide()
MonthCalendar1.Enabled = True
MonthCalendar1.Show()
SaveBtn.Hide()
Addbtn.Hide()
delbtn.Hide()
Backbtn.Hide()
lblMessage.Show()
End Sub
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
t = MonthCalendar1.SelectionRange.Start.Month.ToString & MonthCalendar1.SelectionRange.Start.Day.ToString
Try
If Notetxt.Text = "" Then
If File.Exists(t & ".txt") = True Then
File.Delete(t & ".txt")
End If
End If
If Notetxt.Text.Length > 0 Then
File.WriteAllText(t & ".txt", Notetxt.Text)
MsgBox("SAVE SUCCESS", vbOKOnly)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Addbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Addbtn.Click
Notetxt.Text = "Hi QC Engineer, Golden Sample meet Due date already please change." & Environment.NewLine & "MODEL: " & Environment.NewLine & "START DATE: " & Environment.NewLine & "DUE DATE: " & Environment.NewLine & "APPROVED BY: EAKKACHAI"
End Sub
Private Sub delbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delbtn.Click
Notetxt.Clear()
File.Delete(t & ".txt")
End Sub
End Class
and below is my code for sending email.
Public Class sendEmail
Private Sub sendEmail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Content As String
Content = emailtxt.Text
emailtxt.Text = Reminder.Notetxt.Text
Dim Outlook As New Microsoft.Office.Interop.Outlook.Application
Dim MailItem As Microsoft.Office.Interop.Outlook.MailItem
MailItem = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
With MailItem
.HTMLBody = emailtxt.Text
.Subject = "GOLDEN SAMPLE DUE DATE EXPIRED"
'use the below to change from the default email account
.SentOnBehalfOfName = "your#email.com"
'you can add multiple recipients using .Add()
.Recipients.Add("your#email.com")
'examples of other optional arguments that can be included
' .Attachments.Add([file])
.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh
.Send() 'opens the email for checking prior to sending or use .Send()
End With
End Sub
End Class
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
I've the following code, it's a code that parses an external Log file to a datagridview, however when I load a big file the operation takes time and the form freezes for a bit, what I need is to show a progress bar while it's parsing the log file.
This is the code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using Reader As New Microsoft.VisualBasic.FileIO.
TextFieldParser(TextBox1.Text)
Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), Convert.ToInt32(txtCO.Text), _
Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), Convert.ToInt32(txtAccCode.Text))
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
Dim curRowIndex = dg1.Rows.Add()
' Set the first cell of the new row....
dg1.Rows(curRowIndex).Cells(0).Value = currentRow(0)
dg1.Rows(curRowIndex).Cells(1).Value = currentRow(1)
dg1.Rows(curRowIndex).Cells(2).Value = currentRow(2)
dg1.Rows(curRowIndex).Cells(3).Value = currentRow(3)
dg1.Rows(curRowIndex).Cells(4).Value = currentRow(4)
dg1.Rows(curRowIndex).Cells(5).Value = currentRow(5)
dg1.Rows(curRowIndex).Cells(6).Value = currentRow(6)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
MsgBox("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Add a BackgroundWorker and set its WorkerReportsProgressProperty to True.
Add a ProgressBar.
Then try this code out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim widths() As Integer = { _
Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), _
Convert.ToInt32(txtCO.Text), Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), _
Convert.ToInt32(txtAccCode.Text)}
ProgressBar1.Visible = True
ProgressBar1.Style = ProgressBarStyle.Marquee ' continuos animation
Dim input As New Tuple(Of String, Integer())(TextBox1.Text, widths)
BackgroundWorker1.RunWorkerAsync(input)
Catch ex As Exception
MessageBox.Show("Invalid Width!")
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim input As Tuple(Of String, Integer()) = DirectCast(e.Argument, Tuple(Of String, Integer()))
Try
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(input.Item1)
Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(input.Item2)
Dim currentRow() As String
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
BackgroundWorker1.ReportProgress(-1, New Object() { _
currentRow(0), currentRow(1), currentRow(2), _
currentRow(3), currentRow(4), currentRow(5), _
currentRow(6)})
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MessageBox.Show("Line is not valid and will be skipped." & vbCrLf & vbCrLf & ex.Message)
End Try
End While
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim values() As Object = DirectCast(e.UserState, Object())
dg1.Rows.Add(values)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
ProgressBar1.Style = ProgressBarStyle.Continuous
ProgressBar1.Visible = False
End Sub
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.