Debugging in vb.net? - 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

Related

How to save Received Messages From Gsm Modem to your Mysql Database?

I am trying to save received sms from my modem to MySQL database, and I am using MySQL Workbench for my database.
Here's my functionalities:
1. Auto detect modem
2. Connect modem
3. Send Messages
4. Read Messages
5. Handles (SerialPort Data received)
Here's the Code:1. Auto Detect Modem
'Some Imports
Imports System.Management
Imports System.Threading
Imports System.Text.RegularExpressions
Imports MySql.Data.MySqlClient
Public Class Form1
Dim result() As String
Dim query As String
Dim rcvdata As String = ""
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ports() As String
ports = Split(ModemsConnected(), "***")
For i As Integer = 0 To ports.Length - 2
ComboBox1.Items.Add(ports(i))
Next
End Sub
Public Function ModemsConnected() As String
Dim modems As String = ""
Try
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_POTSModem")
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = modems & (queryObj("AttachedTo") & " - " & queryObj("Description") & "***")
End If
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
Return ""
End Try
Return modems
End Function
'Show Detected or Available modem
Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
Label1.Text = Trim(Mid(ComboBox1.Text, 1, 5))
End Sub
2. Connect/Disconnect Modem
'button connect
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
Try
With SerialPort1
.PortName = Label1.Text
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = True
.ReceivedBytesThreshold = 1
.NewLine = vbCr
.ReadTimeout = 1000
.Open()
End With
If SerialPort1.IsOpen Then
Label3.Visible = True
btnDisconnect.Visible = True
Label3.Text = "Connected - Port " & Label1.Text & " is used"
Else
Label3.Text = "Got some Error, Check your connection with your Modem."
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
'button Disconnect
Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Close()
.Dispose()
Label1.Visible = False
Label3.Visible = False
btnDisconnect.Visible = False
ListView1.Items.Clear()
End With
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
3. Send Messages
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Dim query As String
Try
Connection()
query = "INSERT INTO thesis.tblsentitems (PhoneNumber, message) VALUES('" & txtNumber.Text & "', '" & txtMessage.Text & "')"
sqlcmd = New MySqlCommand(query, conn)
sqlreader = sqlcmd.ExecuteReader
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgs=" & Chr(34) & txtNumber.Text & Chr(34) & vbCrLf)
.Write(txtMessage.Text & Chr(26))
Threading.Thread.Sleep(200)
End With
If rcvdata.ToString.Contains(">") Then
MsgBox("Message Succesfully Sent")
conn.Close()
Else
MsgBox("Got some error!")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
4. Read Messages
Private Sub btnReadsms_Click(sender As System.Object, e As System.EventArgs) Handles btnReadsms.Click
Try
With SerialPort1
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CPMS=""SM""" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGL=""ALL""" & vbCrLf)
Threading.Thread.Sleep(1000)
'MsgBox(rcvdata.ToString)
readmsg()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Save Received message to ListView1
Private Sub readmsg()
Try
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
For i = 1 To UBound(arytextfile)
Dim input As String = arytextfile(i)
Dim pattern As String = "(:)|(,"")|("","")"
result = Regex.Split(input, pattern)
Dim concat() As String
With ListView1.Items.Add("null")
'for index
.SubItems.AddRange(New String() {result(2).ToString})
'for status
.SubItems.AddRange(New String() {result(4).ToString})
'for number
Dim my_string, position As String
my_string = result(6)
position = my_string.Length - 2
my_string = my_string.Remove(position, 2)
.SubItems.Add(my_string)
'for date and time
concat = New String() {result(8)}
.SubItems.AddRange(concat)
'for message
Dim lineoftexts As String
Dim arytextfiles() As String
lineoftexts = arytextfile(i)
arytextfiles = Split(lineoftexts, "+32", , CompareMethod.Text)
.SubItems.Add(arytextfiles(1))
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
5. Handles (SerialPort Data received)
Private Sub SerialPort1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim datain As String = ""
Dim numbytes As Integer = SerialPort1.BytesToRead
For i As Integer = 1 To numbytes
datain &= Chr(SerialPort1.ReadChar)
Next
test(datain)
End Sub
Private Sub test(ByVal indata As String)
rcvdata &= indata
End Sub
Hope someone can Help, please... :/

VB.net - If 1 then "Yes" if 0 then "no"

I have Database Software I am trying to make. The problem is I can't seem to find how to make this work, i'm new to this whole thing and have figured a lot out on my own but I can't seem to do this simple task?
I have a listView that displays the data from the SQl everything works great EXCEPT I need the dropdaown box the say yes or no but import into the SQL database a 1 or 0 and also in my list view i need it to display a Yes or a No instead of a 1 or a 0 ? Thanks IN Advance
Code:
Imports System.Data.SqlClient
Imports System.Data
Public Class cmListAll
Dim cn As New SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Private Sub frmReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With Me.cboActive
.Items.Add("Yes")
.Items.Add("No")
.SelectedIndex = 0
End With
Call connectMeToSQLServer("Data Source=Database;Initial Catalog=db_XXX;Integrated Security=False;Uid=sa; Pwd=PASS;")
Call showList()
End Sub
Private Sub cboActive_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub
Private Sub cboACTIVE_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.txtCredentials.Focus()
End Sub
Sub connectMeToSQLServer(ByVal cnString As String)
Try
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = cnString
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Function INC() As Boolean
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Or TypeOf t Is ComboBox Then
End If
If t.Text = "" Then
INC = True
End If
Next
End Function
Sub showList()
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers]"
dr = cmd.ExecuteReader
Me.ListView1.Items.Clear()
While dr.Read
With Me.ListView1
.Items.Add(dr(0))
With .Items(.Items.Count - 1).SubItems
.Add(dr(1))
.Add(dr(2))
.Add(dr(3))
.Add(dr(4))
End With
End With
End While
dr.Close()
End Sub
Sub clearMe()
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
Me.cmdNew.Enabled = True
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = False
Me.cmdDelete.Enabled = False
Me.cboActive.SelectedIndex = 0
End If
Next
End Sub
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
End If
Next
Me.cmdNew.Enabled = False
Me.cmdSave.Tag = "SAVE"
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = True
Me.GroupBox2.Enabled = True
Me.txtfirstname.Focus()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Select Case Me.cmdSave.Tag
Case "SAVE"
If INC() = True Then
MsgBox("Please Complete All Fields!", MsgBoxStyle.Exclamation, "")
Exit Sub
Else
cmd = New SqlCommand
cmd.CommandText = "Insert Into [Case Managers](Firstname,Lastname,Credentials,Active) Values('" & Me.txtfirstname.Text & "', '" & Me.txtlastname.Text & "', '" & Me.txtCredentials.Text & "', '" & Me.cboActive.Text & "' )"
cmd.Connection = cn
cmd.ExecuteNonQuery()
MsgBox("Successfully Save!", MsgBoxStyle.Information, "")
End If
Case Else
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Update [Case Managers] Set firstname='" & Me.txtfirstname.Text & "', lastname='" & Me.txtlastname.Text & "', credentials='" & Me.txtCredentials.Text & "', active='" & Me.cboActive.Text & "' Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & ""
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "")
End Select
clearMe()
showList()
End Sub
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers] Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & " "
dr = cmd.ExecuteReader
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = dr(4)
dr.Close()
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
If MsgBox("Delete This Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Delete from [Case Managers] Where CaseMangerID =" & Me.ListView1.SelectedItems(0).Text & " "
cmd.ExecuteNonQuery()
MsgBox("Successfully Deleted!", MsgBoxStyle.Information, "")
Me.cmdDelete.Enabled = False
Me.cmdSave.Enabled = False
Call clearMe()
Call showList()
Else
Exit Sub
End If
End Sub
I assume you're looking at this line:
Me.cboActive.Text = dr(4)
? That's the only thing that looked to me like it might be displaying a yes/no field. You could just put a simple If/Else block there, but as there are several other significant flaws in how this code is structured, I thought it would be useful to re-write that whole method for you:
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'Would be better to specify column names here
Dim sql As String = "Select * from [Case Managers] Where CaseMangerID = #CaseManager"
'Best practices in most cases call for creating a new connection object for each query
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'This is how to do string substitution in sql to protect against sql injection
cmd.Parameters.Add("#CaseManager", SqlDbType.Int).Value = CInt(Me.ListView1.SelectedItems(0).Text)
Using dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = If(dr(4)=0,"No","Yes")
dr.Close()
End Using
End Using 'No need to close the connection. The Using block takes care of it
'The old code would have the left the connection open if an exception was thrown,'
' which could eventually lock you out of the database
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
You'll need to do something similar later on to invert this for updates/inserts.
You can use DisplayMember/ValueMember pair:
Dim dict As New Dictionary(Of Integer, String)
dict.Add(0, "No")
dict.Add(1, "Yes")
With Me.cboActive
.DisplayMember = "Value"
.ValueMember = "Key"
.DataSource = dict.ToList()
.SelectedIndex = 0
End With
Dictionary may not the best choice of class here, but works as a proof of concept.
Then just use cboActive.SelectedValue and pass that to the SQL query.

Calling and executing a stored procedure from sql into a vb.net textbox

I have created the following stored procedure in SQL Server:
CREATE Procedure CalcTotal
#InvoiceID Varchar(4)
As
Declare #Total int
Begin
SELECT
#Total = (TransportFee + EquipmentFee + LabourFee)
FROM
Invoice
WHERE
InvoiceID = #invoiceID
UPDATE Invoice
SET Total = #Total
WHERE InvoiceID = #invoiceID
END
My code for my form on Visual Basic are:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Invoice
Dim sqlConn As New SqlConnection With {.ConnectionString = "Data Source=Hamsheed;Initial Catalog=assignment;Integrated Security=True"}
Dim sqlstr As String = "Select * From Invoice"
Dim MaxRows As Integer
Dim RowIndex As Integer = 0
Dim dt As New DataTable
Private Sub Invoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
DataAdapter.Fill(dt)
DataAdapter.Dispose()
MaxRows = dt.Rows.Count
InvoiceDetails()
cmbSearch.DataSource = dt
cmbSearch.DisplayMember = "FirstName"
End Sub
Sub InvoiceDetails()
txtInvoiceID.Text = CStr(dt.Rows(RowIndex)("InvoiceID"))
txtClientID.Text = CStr(dt.Rows(RowIndex)("ClientID"))
txtEmployeeID.Text = CStr(dt.Rows(RowIndex)("EmployeeID"))
txtFillInDate.Text = CStr(dt.Rows(RowIndex)("FillInDate"))
txtTransportFee.Text = CStr(dt.Rows(RowIndex)("TransportFee"))
txtEquipmentFee.Text = CStr(dt.Rows(RowIndex)("EquipmentFee"))
txtLabourFee.Text = CStr(dt.Rows(RowIndex)("LabourFee"))
txtTotal.Text = CStr(dt.Rows(RowIndex)("Total"))
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim InvoiceID As String = txtInvoiceID.Text
Dim ClientID As String = txtClientID.Text
Dim EmployeeID As String = (txtEmployeeID.Text)
Dim FillInDate As Date = CDate(txtFillInDate.Text)
Dim TransportFee As Integer = CInt(txtTransportFee.Text)
Dim EquipmentFee As Integer = CInt(txtEquipmentFee.Text)
Dim LabourFee As Integer = CInt(txtLabourFee.Text)
Dim Total As Integer = CInt(txtTotal.Text)
If CStr(dt.Rows(RowIndex)("paymentmethod")) = "Card" Then
radCard.Select()
ElseIf CStr(dt.Rows(RowIndex)("paymentmethod")) = "Cash" Then
radCash.Select()
Else
radCredit.Select()
End If
Dim sqlQuery As String = ("Exec Insert_Invoice #InvoiceID = ' " & InvoiceID & " ', #ClientID = '" & ClientID & "',#EmployeeID ='" & EmployeeID & "', #FillInDate ='" & FillInDate & "',#TransportFee='" & TransportFee & "',#EquipmentFee = '" & EquipmentFee & "',#LabourFee= '" & LabourFee & "',#Total= '" & Total)
Dim sqlcmnd As New SqlCommand(sqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dt.Rows(RowIndex)("InvoiceID") = CStr(txtInvoiceID.Text)
dt.Rows(RowIndex)("ClientID") = CStr(txtClientID.Text)
dt.Rows(RowIndex)("EmployeeID") = CStr(txtEmployeeID.Text)
dt.Rows(RowIndex)("FillInDate") = CStr(txtFillInDate.Text)
dt.Rows(RowIndex)("TransportFee") = CStr(txtTransportFee.Text)
dt.Rows(RowIndex)("EquipmentFee") = CStr(txtEquipmentFee.Text)
dt.Rows(RowIndex)("LabourFee") = CStr(txtLabourFee.Text)
dt.Rows(RowIndex)("Total") = CStr(txtTotal.Text)
Dim sqlquery As String = "exec edit_invoice '" & txtInvoiceID.Text & "', " & txtLabourFee.Text & ", " & txtTransportFee.Text & ", " & txtEquipmentFee.Text & ", '" & txtpaymentMethod.Text & "', '" & txtClientID.Text & "', '" & txtEmployeeID.Text & "', '" & txtFillInDate.Text & "', '" & txtTotal.Text & "'"
Dim sqlcmnd As New SqlCommand(sqlquery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtInvoiceID.Clear()
txtClientID.Clear()
txtEmployeeID.Clear()
txtFillInDate.Clear()
txtTransportFee.Clear()
txtEquipmentFee.Clear()
txtLabourFee.Clear()
txtTotal.Clear()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If RowIndex <> MaxRows - 1 Then
RowIndex += 1
InvoiceDetails()
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
RowIndex = MaxRows - 1
InvoiceDetails()
End Sub
Private Sub btnMainMenu_Click(sender As Object, e As EventArgs) Handles btnMainMenu.Click
SecretaryMainMenu.Show()
Me.Hide()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim invoiceID As String = txtInvoiceID.Text
Dim SqlQuery As String = ("EXECUTE Delete_Invoice #InvoiceID = '" & InvoiceID & "'")
Dim cmd As New SqlCommand(SqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = cmd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Record Deleted")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
dt.Rows(RowIndex).Delete()
End Sub
Sub Save()
Dim dataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
Dim commandbuilder As New SqlCommandBuilder(dataAdapter)
dataAdapter.Update(dt)
dataAdapter.Dispose()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim searchitem As String = InputBox("Input Search invoice ID: ", "Search by ID")
Dim sresult As Boolean = False
searchitem = searchitem.Trim.ToUpper
For i As Integer = 0 To MaxRows - 1
If CStr(dt.Rows(i)("invoiceid")).ToUpper = searchitem Then
sresult = True
RowIndex = i
InvoiceDetails()
End If
Next
If sresult = False Then
MsgBox("No result found", MsgBoxStyle.OkOnly, "Information")
End If
End Sub
Private Sub txtinvoice_validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtInvoiceID.Validating
If Not txtInvoiceID.Text Like "I###" Then
e.Cancel = True
ErrorProvider1.SetError(txtInvoiceID, "Improper ID format")
End If
End Sub
Private Sub txtinvoice_validated(ByVal sender As Object, ByVal e As EventArgs) Handles txtInvoiceID.Validated
ErrorProvider1.SetError(txtInvoiceID, "")
End Sub
End Class
Now I want to call the stored procedure into the textbox Total, which will compute the 'transportFee, EquipmentFee and Labourfee' costs, and display the total into the textbox of txtTotal.Text
How do I write that piece of code?
use executescalar: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
remember to set the commandtype property of the command to stored procedure

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.

"Object reference not set" error when creating a form

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.