Alright, here is my issue.
Working on a Inventory Control program, and got it mostly done, when a wild bug appears.
The system will check out a item, but will not check it back in, even though it throws all the proper messages that it does check the item in.
What's worse, is that the SQL statement is encapsulated in a try-catch class and acts as if nothing is wrong, and does not throw an exception.
And this is just a functional build, not a streamlined one, so it looks a little rough.
The statement in question is:
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
I am sure it is something very very obvious, but I have been rebuilding and staring at it for so long, I am likely glossing over a glaring hole in it.
Option Strict On
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Public EmpIDFlag As Boolean
Public ItemBCode As Boolean
Public CheckFlag As Boolean
Public dEmpID As Double
Public sEmpID As String
Public dbEmpID As Double
Public dBarcode As Double
Public sBarcode As String
Public sFirstName As String
Public sLastName As String
Public sFullName As String
Public sItem As String
Public sCheckedOut As String
Public sCheckedOutBy As String
Public OleDbConn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\rcassel\Documents\Visual Studio 2012\Projects\Inventory Control\Inventory Control\Inventory Control2.accdb;")
Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
dEmpID = (Val(TextBox1.Text))
'Checks to see if someone entered a Badge
If dEmpID = Nothing Then
MsgBox("You must scan your Badge!", MsgBoxStyle.OkOnly)
TextBox1.Focus()
Else
sEmpID = dEmpID.ToString
'Fire Query into Database
Try
OleDbConn.Open()
Dim OleEmp As New OleDbCommand("SELECT [First Name],[Last Name],[Employee ID] FROM Contacts WHERE [Employee ID]=" + sEmpID + "", OleDbConn)
Dim r1 As OleDbDataReader = OleEmp.ExecuteReader()
While r1.Read()
sFirstName = CStr(r1("First Name"))
sLastName = CStr(r1("Last Name"))
dbEmpID = CInt(r1("Employee ID"))
End While
r1.Close()
Catch ex As Exception
'MsgBox("Cannot Pull Data." & vbCrLf & ex.Message)
End Try
If dbEmpID = Nothing Then
MsgBox("You are not Authorised to use this device. This activity has been logged.", MsgBoxStyle.OkOnly)
Else
Me.ListBox1.Items.Add(sFirstName)
Me.ListBox1.Items.Add(sLastName)
Me.ListBox1.Items.Add(sEmpID)
TextBox2.Focus()
End If
OleDbConn.Close()
End If
End Sub
'Item Barcode
'Private Sub TextBox2_LostFocus(sender As Object, e As EventArgs) Handles TextBox2.LostFocus
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
dBarcode = (Val(TextBox2.Text))
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
sBarcode = dBarcode.ToString()
OleDbConn.Open()
Try
Dim OleItem As New OleDbCommand("SELECT [Item],[Checked Out],[Checked out Last by] FROM Assets WHERE [ID Number]=" + sBarcode + "", OleDbConn)
Dim r2 As OleDbDataReader = OleItem.ExecuteReader()
While r2.Read()
sItem = CStr(r2("Item"))
sCheckedOut = CStr(r2("Checked Out"))
sCheckedOutBy = CStr(r2("Checked out Last by"))
End While
ItemBCode = True
'Set Checkout Flag, this will be called later by the Check In/Check Out button
If sCheckedOut = "Checked Out" Then
CheckFlag = True
End If
r2.Close()
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
If ItemBCode = True Then
Me.ListBox2.Items.Add(sItem)
Me.ListBox2.Items.Add(sCheckedOut)
Me.ListBox2.Items.Add(sCheckedOutBy)
End If
OleDbConn.Close()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
'This is the "Check In" button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag Then
Try
OleDbConn.Open()
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked in!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked in!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
'This is the "Check Out" button
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag = False Then
Try
sFullName = String.Format("{0} {1}", sFirstName, sLastName)
OleDbConn.Open()
Dim OleCheckOut As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked Out',[Checked out Last by] ='" + sFullName + "' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked Out!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked Out!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
End Class
You never execute your update commands:
OleCheckIn.ExecuteNonQuery()
OleCheckOut.ExecuteNonQuery()
Also, use parameters. You are exposing your system to SQL injection.
Related
The code I tried to convert from a C# code to VB.Net code is attached.
I was able to add the headers to a ListView.
I couldn't get the DeviceID and Caption values.
There is a loop inside the code. Since I converted the code from C# code to VB.Net with a converter, there might be deficiencies. Where am I making a mistake or what is missing in this code? I just couldn't succeed.
Find device instance path:
Imports System
Imports System.Collections
Imports System.Management
Imports System.Collections.Generic
Imports System.Windows.Forms
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.SelectedItem = "Win32_PnPEntity"
End Sub
#Disable Warning CA1822
Private Sub InsertInfo(ByVal Key As String, ByRef lst As ListView, ByVal DontInsertNull As Boolean)
#Enable Warning CA1822
lst.Items.Clear()
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(("select DeviceID, Caption from " + Key))
Try
For Each share As ManagementObject In searcher.Get
Dim grp As ListViewGroup
Try
grp = lst.Groups.Add(share("Name").ToString, share("Name").ToString)
Catch 'As System.Exception
grp = lst.Groups.Add(share.ToString, share.ToString)
End Try
If share.Properties.Count <= 0 Then
MessageBox.Show("No Information Available", "No Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
Return
End If
For Each PC As PropertyData In share.Properties
Dim item As ListViewItem = New ListViewItem(grp)
If (lst.Items.Count Mod 2) <> 0 Then
item.BackColor = Color.White
Else
item.BackColor = Color.WhiteSmoke
End If
item.Text = PC.Name
If PC.Value IsNot Nothing AndAlso PC.Value.ToString <> "" Then
Select Case PC.Value.GetType.ToString
Case "System.String[]"
Dim str() As String = CType(PC.Value, String())
Dim str2 As String = ""
Dim st As String
For Each st In str
str2 += (st + " ")
Next
item.SubItems.Add(str2)
Case "System.UInt16[]"
Dim shortData() As System.UInt16 = CType(PC.Value, System.UInt16())
Dim tstr2 As String = ""
For Each st As System.UInt16 In shortData
tstr2 += (st.ToString + " ")
Next
item.SubItems.Add(tstr2)
Case Else
item.SubItems.Add(PC.Value.ToString)
End Select
ElseIf Not DontInsertNull Then
item.SubItems.Add("No Information available")
Else
'TODO: Warning!!! continue Else
End If
lst.Items.Add(item)
Next
Next
Catch exp As Exception
MessageBox.Show(("can't get data because of the followeing error " & vbLf + exp.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
Private Shared Sub RemoveNullValue(ByRef ListView1 As ListView)
For Each item As ListViewItem In ListView1.Items
If (item.SubItems(1).Text = "No Information available") Then
item.Remove()
End If
Next
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
RemoveNullValue(ListView1)
Else
InsertInfo(ComboBox1.SelectedItem.ToString, ListView1, CheckBox1.Checked)
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
InsertInfo(ComboBox1.SelectedItem.ToString, ListView1, CheckBox1.Checked)
End Sub
End Class
I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted
I want to take a value entered by the user and validate it against known values in a database.
I'm using VB.net (VS 2010) as a front end winform and dumping data into MSAccess. I have a table with values such as min weight and max weight, the user will enter a weight, and it needs to fall between the min weight and max weight values in the table.
I'm already created an open connection with the database I need, I guess I just don't know enogh VB.net and SQL to make it do what I want.
I want to have the user enter the Primary key of the table with the min weight and max weights and then use that to bring in the min max weights, then check the weight the user entered against the min max weights.
Here is all the code; the only really relevant code is the validate button click at the bottom. I just thought possibly this would give more context. Any point in the right direction will help, even if it gives me better keywords to google. Thanks!
Imports System.Data.OleDb
Public Class Form1
Dim dbInsert As New OleDb.OleDbCommand
Dim dbConnect As New OleDb.OleDbConnection
Dim Line As String = Environment.NewLine
Dim Job As VariantType
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
dbConnect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\crabara\Desktop\Project Alpha 3\MDB.accdb;Persist Security Info=False;"
dbConnect.Open()
Catch ex As Exception
MessageBox.Show(ex.Message + Line + "Main Database Not Found" + Line + "Check form_AccessMaintenance source code" + Line + "Database Path", "Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End Sub
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Part As String, Job As String, Emp As String, Weight As String, Oven As String
Part = txtPart.Text
Job = txtJob.Text
Emp = txtEmp.Text
Weight = txtWeight.Text
Oven = txtOven.Text
If ((Job.StartsWith("JH") And Job.Length = 10) Or Job.Equals("MT")) = False Then
MsgBox("Please input the correct Job Number.")
txtJob.Clear()
txtJob.Focus()
Exit Sub
ElseIf Part.Length = 0 Then
MsgBox("Please input the correct Part Number.")
txtPart.Clear()
txtPart.Focus()
Exit Sub
ElseIf Emp.Length = 0 Then
MsgBox("Please input the correct Employee Number.")
txtEmp.Clear()
txtEmp.Focus()
Exit Sub
ElseIf Weight.Length = 0 Then
MsgBox("Please input the correct Weight.")
txtWeight.Clear()
txtWeight.Focus()
Exit Sub
ElseIf Oven.Length = 0 Then
MsgBox("Please input the correct Oven Number.")
txtOven.Clear()
txtOven.Focus()
Exit Sub
End If
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Part"
dbInsert.Parameters.Item("Part").Value = txtPart.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Job"
dbInsert.Parameters.Item("Job").Value = txtJob.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Emp"
dbInsert.Parameters.Item("Emp").Value = txtEmp.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Weight"
dbInsert.Parameters.Item("Weight").Value = txtWeight.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Oven"
dbInsert.Parameters.Item("Oven").Value = txtOven.Text
Try
dbInsert.CommandText = "INSERT INTO Foam(Part,Job,Emp,Weight,Oven) VALUES(txtPart.Text, txtJob.Text, txtEmp.Text, txtWeight.Text, txtOven.Text);"
dbInsert.CommandType = CommandType.Text
dbInsert.Connection = dbConnect
dbInsert.ExecuteNonQuery()
MessageBox.Show("Data has been successfully submitted" + Line + txtPart.Text)
txtPart.Clear()
txtJob.Clear()
txtEmp.Clear()
txtWeight.Clear()
txtOven.Clear()
Control.MousePosition.Equals(txtPart)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub txtJob_GotFocus(sender As Object, e As System.EventArgs)
txtJob.Clear()
End Sub
Private Sub txtJob_LostFocus(sender As Object, e As System.EventArgs)
Dim Job2 As String
Job2 = txtJob.Text
If txtJob.Text.Length = 8 Then
txtJob.Text = "JH" + Job2
End If
End Sub
Private Sub btnValidate_Click_1(sender As System.Object, e As System.EventArgs) Handles btnValidate.Click
Dim Pcr As Integer
Pcr = txtPcr.Text
Try
dbInsert.CommandText = "SELECT MoldVinylWeightMin FROM PROCESS_INFO where PCRNumber= '" & txtPcr.Text & "'"""
'How can I get this data I've selected into a variable I can work with, also not sure if the above command actually works also this only gives me the min I need the max too
dbInsert.CommandType = CommandType.Text
dbInsert.Connection = dbConnect
dbInsert.ExecuteNonQuery()
MessageBox.Show("Data has been successfully submitted" + Line + txtPart.Text)
Catch ex As Exception
End Try
End Sub
End Class
I think below code will help you
Dim table = New DataTable()
Dim adp As New System.Data.OleDb.OleDbDataAdapter("SELECT MoldVinylWeightMin FROM PROCESS_INFO where PCRNumber= '" & txtPcr.Text & "'", dbConnect)
adp.Fill(table)
If table.Rows.Count <> 0 Then
If table.Rows(0).Item("MoldVinylWeightMin") <> YourField Then
Display the message
End If
Else
No record found
End If
using this block you can get the record from the database and apply you validation.
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
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.