Clearing text boxes - vba

I compiled the following little application only I want all the textpoxes cleard when the tabs areswitched by the user how can this be achieved?
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox2.Text) + "," + " " + "*" + (TextBox1.Text))
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox3.Text) + "," + " " + "START " + (TextBox4.Text) + ", 1,,")
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox5.Text) + "," + " " + "START " + (TextBox6.Text) + ", 1,,")
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Class

Public Sub ClearTextBoxes(frmClearMe As Form)
Dim txt As Control
For Each txt In frmClearMe
If TypeOf txt Is TextBox Then txt.Text = ""
Next
End Sub

Related

Displaying file properties

Is possible to display file properties with full path and date. I would like to add file size and/or hash value of the file to the output (if possible) the data will be written to a text file not done yet I want to get the basic operation working first. This will be used as a file monitor for USB drives when all is said and done.
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
Private WithEvents objWatcher As New clsFSW()
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents cmdStart As System.Windows.Forms.Button
Friend WithEvents cmdStop As System.Windows.Forms.Button
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtFolder As System.Windows.Forms.TextBox
Friend WithEvents chkSubFolders As System.Windows.Forms.CheckBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.cmdStart = New System.Windows.Forms.Button()
Me.cmdStop = New System.Windows.Forms.Button()
Me.Label1 = New System.Windows.Forms.Label()
Me.txtFolder = New System.Windows.Forms.TextBox()
Me.chkSubFolders = New System.Windows.Forms.CheckBox()
Me.SuspendLayout()
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(32, 8)
Me.TextBox1.Multiline = True
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.TextBox1.Size = New System.Drawing.Size(392, 240)
Me.TextBox1.TabIndex = 0
Me.TextBox1.Text = ""
'
'cmdStart
'
Me.cmdStart.Location = New System.Drawing.Point(120, 336)
Me.cmdStart.Name = "cmdStart"
Me.cmdStart.TabIndex = 1
Me.cmdStart.Text = "Start Watch"
'
'cmdStop
'
Me.cmdStop.Location = New System.Drawing.Point(216, 336)
Me.cmdStop.Name = "cmdStop"
Me.cmdStop.TabIndex = 2
Me.cmdStop.Text = "Stop Watch"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(6, 272)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(93, 13)
Me.Label1.TabIndex = 3
Me.Label1.Text = "Folder to Monitor:"
'
'txtFolder
'
Me.txtFolder.Location = New System.Drawing.Point(110, 272)
Me.txtFolder.Name = "txtFolder"
Me.txtFolder.Size = New System.Drawing.Size(184, 20)
Me.txtFolder.TabIndex = 4
Me.txtFolder.Text = ""
'
'chkSubFolders
'
Me.chkSubFolders.Location = New System.Drawing.Point(312, 272)
Me.chkSubFolders.Name = "chkSubFolders"
Me.chkSubFolders.Size = New System.Drawing.Size(128, 24)
Me.chkSubFolders.TabIndex = 6
Me.chkSubFolders.Text = "Include Subfolders"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(464, 373)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.chkSubFolders, Me.txtFolder, Me.Label1, Me.cmdStop, Me.cmdStart, Me.TextBox1})
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "File System Watcher Class Demo"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmdStop.Enabled = False
With objWatcher
End With
End Sub
Private Sub cmdStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStart.Click
Dim sDir As String
sDir = txtFolder.Text
If IO.Directory.Exists(sDir) Then
objWatcher.FolderToMonitor = sDir
objWatcher.StartWatch()
cmdStop.Enabled = True
cmdStart.Enabled = True
chkSubFolders.Enabled = True
Else
MessageBox.Show("Folder does not exist!")
End If
End Sub
Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
objWatcher.StopWatch()
cmdStop.Enabled = True
cmdStart.Enabled = True
chkSubFolders.Enabled = True
End Sub
Private Sub chkSubFolders_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSubFolders.CheckedChanged
objWatcher.IncludeSubfolders = (chkSubFolders.Checked = True)
End Sub
Private Sub objWatcher_FileCreated(ByVal FullPath As String) Handles objWatcher.FileCreated
TextBox1.Text &= "File Created: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileChanged(ByVal FullPath As String) Handles objWatcher.FileChanged
TextBox1.Text &= "File Changed: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileDeleted(ByVal FullPath As String) Handles objWatcher.FileDeleted
TextBox1.Text &= "File Deleted: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileRenamed(ByVal OldFileName As String, ByVal newFileName As String) Handles objWatcher.FileRenamed
TextBox1.Text &= "File Rename: " & OldFileName & " to " & newFileName & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileWatchError(ByVal ErrMsg As String) Handles objWatcher.FileWatchError
TextBox1.Text &= "The following error occurred: " & ErrMsg & vbCrLf
End Sub
End Class

tcp connection with machine via ethernet using vb.net

I want to make a simple formapp using vb.net to send ASCII strings to a machine, that responds after every command. i.e., if i send "AA" it responds "123".
I can already open the connection cause if i check the connection with hyperterminal it says that the port is already being used. Yet, when i send commands i have no answer back.
I kinda adapted the template codes for server/client chat with tcp:
Imports System.Net.Sockets
Imports System.Threading
Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = "
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
If Listener.Pending = True Then
Message = ""
Client = Listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream())
While Reader.Peek > -1
Message = Message + Convert.ToChar(Reader.Read()).ToString
End While
RichTextBox1.ForeColor = Color.Black
RichTextBox1.Text += Message + vbCrLf
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSend.Click
If txtName.Text = "" Or cmbAddress.Text = "" Then
MessageBox.Show("All Fields must be Filled", _
"Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Try
Client = New TcpClient(cmbAddress.Text, 65535)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write(txtName.Text & " Says: " & txtmessage.Text)
Writer.Flush()
RichTextBox1.Text += (txtName.Text & " Says: " & txtmessage.Text) + vbCrLf
txtmessage.Text = ""
Catch ex As Exception
Console.WriteLine(ex)
Dim Errorresult As String = ex.Message
MessageBox.Show(Errorresult & vbCrLf & vbCrLf & _
"Please Review Client Address", _
"Error Sending Message", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
is there a muuuuuuuch better way to do this? i read about .net.sockets but i coulndt get out of this.
and the manuals say nothing about how the machine operates. if it's a client, server, host.. can someone help me here? thank you !
Imports System.Net
Imports System.Net.Sockets
Imports System.Text.UTF7Encoding
Public Class Form1
Dim open As TcpListener
Dim server As TcpListener
Dim client, host As TcpClient
Dim dati, hdat As NetworkStream
Dim ip As String = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ip = TextBox1.Text
client = New TcpClient
client.Connect(ip, 2101)
If client.Connected = True Then
dati = client.GetStream
MsgBox("Connected", MsgBoxStyle.Information)
Button1.Enabled = False
Timer1.Start()
Else
MsgBox("Error", MsgBoxStyle.Critical)
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If client.Available > 0 Then
Dim t(client.Available - 1) As Byte
dati.Read(t, 0, t.Length)
Dim testo As String = UTF7.GetString(t)
RichTextBox1.Text += vbCrLf & "server : " & testo & vbCrLf
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t() As Byte = UTF7.GetBytes(TextBox2.Text & vbCrLf)
dati.Write(t, 0, t.Length)
RichTextBox1.Text += vbCrLf & TextBox2.Text & vbCrLf
End Sub
End Class

search and count occurances of a word in a textbox string

Right now I have two textboxes. One is the input and the other the text string. It functions perfectly. Is there a way to get rid of the input box and have the "searched" word in the code so when I hit a button it gives the result.
Private Function FindWords(ByVal TextSearched As String, ByVal Paragraph As String) As Integer
Dim location As Integer = 0
Dim occurances As Integer = 0
Do
location = TextSearched.IndexOf(Paragraph, location)
If location <> -1 Then
occurances += 1
location += Paragraph.Length
End If
Loop Until location = -1
Return occurances
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
There are a couple of small problems that you'll might see of you turn on option strict in your project's compile settings. Your function returns an integer. To properly assign it to a textbox label, you should really add .ToString to the end of the assignment like this
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text).ToString
So leaving you code as you wrote it, in this sub, you just want to pass a string as the parameter for the text to find?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
Just change it to this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim searchString as string="Hello" 'or whatever string you want to use
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(searchString, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
but it might be better to change it a bit more so that your function only gets executed once if you want to display a messagebox with the number of occurences - like this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim searchCount as Integer
dim searchString as string="Hello" 'or whatever string you want to use
Label1.Text = TextBox2.Text ' display result
searchCount = FindWords(searchString, TextBox2.Text)
Label2.Text = searchcount.ToString
' MsgBox("The word " & TextBox2.Text & " has occured " & searchcount.Tostring & " times!!")
End Sub

Vb.net Save data from datagridview to txt and load it

i'am new programmer and just studying about Visual Basic, and to complete my exams
The Data i have
Tool_1 screwdriver
Tool_2 screw
Tool_3 Magnet
And many more
i've create project, it have Data Grid View(two columns, Tools & Names) and two Button(btSave & btOpen)
i just try it with this code
Private Sub btSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btSave.Click
SaveGridData(DataGridView1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub btOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btOpen.Click
LoadGridData(DataGridView1, ThisFilename)
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub
When i save the file it's no problem the txt file is ok, but when i want to load Text "Tool_1 Screwdriver" is not split but is in "Tools" Column
there is a solution to this ?
use this insetad of your loop in loadgriddata
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
dim str as string()
str=thisline.split(" ")
ThisGrid.Rows.Add(str(0),str(1))
Next
hope it helps.
Hey I struggled with this aswell, but I have some usefull code:
export listview:
System.IO.Directory.CreateDirectory("C:\RS Account Maker\Accounts" & "\")
SaveFileDialog1.ShowDialog()
Dim Path As String = SaveFileDialog1.FileName
Dim AllItems As String = ""
Try
For Each item As ListViewItem In ListView1.Items
AllItems = AllItems & item.Text & "#" & item.SubItems(1).Text & "#" & item.SubItems(2).Text & vbNewLine
Next
AllItems = AllItems.Trim
Catch ex As Exception
End Try
Try
If My.Computer.FileSystem.FileExists(Path) Then
My.Computer.FileSystem.DeleteFile(Path)
End If
My.Computer.FileSystem.WriteAllText(Path, AllItems, False)
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
import listview:
OpenFileDialog1.ShowDialog()
Dim Path As String = OpenFileDialog1.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
For Each line As String In ItemLines.Lines
Dim a1() As String = line.Split("#")
Dim ItemName As String = a1(0)
Dim SubItem1 As String = a1(1)
Dim SubItem2 As String = a1(2)
Dim Item As New ListViewItem(ItemName)
Item.SubItems.Add(SubItem1)
Item.SubItems.Add(SubItem2)
ListView1.Items.AddRange(New ListViewItem() {Item})
Next
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
The following line is wrong.
ThisGrid.Rows.Add(Split(THisLine, " "))
The above code was amended as follows.
Dim ThisFilename As String = Application.StartupPath & "\MyData.dat"
Private Sub butSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveGridData(Datagrid1, ThisFilename)
End Sub
Private Sub butLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
LoadGridData(Datagrid1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, ControlChars.Tab))
Next
End Sub

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.