the connection property has not been initialized - sql

I'm trying to run this code for my user interfaces, I connected the interface with my database and I did everything correctly. But the problem is this error keeps showing and I have no clue in how to fix it.
The error says "the connection property has not been initialized"
And this is my code,
Public Class ManageBus
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
txtbus.Text = Nothing
txtdriver = Nothing
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
End
End Sub
Private Sub btnadd_Click(sender As Object, e As EventArgs) Handles btnadd.Click
Try
OracleConnection1.Open()
Dim command As String
command = "insert into BUS(Bus_ID, Driver_ID)" _
& " values('" & txtbus.Text & "', '" _
& txtdriver.Text & ")"
OracleDataAdapter1.InsertCommand.CommandText = command
lblsql.Text = command
OracleDataAdapter1.InsertCommand.ExecuteNonQuery()
MsgBox("Insert Successful", MsgBoxStyle.Information, "Insert Status")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
OracleConnection1.Close()
End Try
End Sub

You need to initialize the connectionstring for the connection to setup the connection. For example:
Dim OracleConnection1 As New OracleConnection("Data Source=ORCL;User Id=test;Password=test;");
OracleConnection1.Open();

Related

How to delete a file used by another Process

Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
End Class
Above code give me an error message:
image is used in another process, can't be deleted
when I delete the image file. The image is assigned to a PictureBox with selection event of the DataGridView. Since I have deleted the DataGridView row, as shown in the above code, it changes the image in the PictureBox.
Here I am unable to delete the image file related to the removed row.
Please guide and let me know if you need any further details.

Deletion of image from folder that is referenced to picture box

sorry i have to rewrite this question as i did not get any update on my same question posted previously.
Below is the code where I'm inserting some data into Ms Access database in visual studio using vb. Net.
When i insert the data i also browse the image for that item and save into the folder that is located under project directory for universal access.
There is a datagridview which displays the data which was inserted to access databas alog with the image in picture box. Whenever the the datagrid view selection is change it display the picure into picture box.
I am having a trouble when i want to delete the data along with image located in project folder as it show the error that 'file used by another process, cant be deleted'
Since i have referenced that image to my picture box, it can not be deleted directly. So here I'm looking for a solution which can display the clone of image in picture box instead of real object.
Below is my code
Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
frmTable.Show()
End Sub
End Class

check database connection using background worker

I already banging my head with this problem, I use backgroundWorker to check if database is OPEN and here's my code for that:
Public Class Form1
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
Dim sqlconnection As New SqlConnection("Data Source=" & My.Settings.Server & ";Initial Catalog=" & My.Settings.Database & ";Integrated Security=false;user id=" & My.Settings.Username & ";password=" & My.Settings.Password & ";Connection Timeout=5;")
Dim connectionStatus As String
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'I store my database information to my.settings then display it on textboxes for manipulation
TextBox1.Text = My.Settings.Server
TextBox2.Text = My.Settings.Database
TextBox3.Text = My.Settings.Username
TextBox4.Text = My.Settings.Password
'just getting my computer name
lblCompName.Text = System.Windows.Forms.SystemInformation.ComputerName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
If sqlconnection.State = ConnectionState.Closed Then
sqlconnection.Open()
connectionStatus = "Online"
'sqlconnection.Open()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: online")
End If
Catch ex As Exception
connectionStatus = "Offline"
sqlconnection.Close()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: offline")
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
Label1.Text = "Database Status: " & connectionStatus
Else
Label1.Text = "Database Status: " & connectionStatus
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
end class
In my code above it does actually works, it does display "database is online/offline" when restarting my program within the visual studio but when I run the program then turn-off/disable my network connection(my database is on other computer) it always display "Database is ONLINE" but I'm pretty sure that there is already no connection between my pc and database(because I PING it) so it must be display as "Database is oFFLINE".
Did I missed something regarding of using backgroundWOrker? Oh BTW, I'm new in using BackgroundWorker.
Any help or alternative solutions is much appreciated thanks!

Application with two forms is not showing

I am creating a form application using Visual Studio Express VB 2008 and SQL server 2008. I have two forms. When the program start is not showing me any form. What is to be done that I could use two forms as one program. For example, in one form I want to insert data type state, city .. and the other to use the same information for something else. But like I said, my first step is to see both forms in one program. What should I do to make it work
Imports System.Data.Sql
Imports System.Data.SqlClient
' This is my main form called form1 and through it I want to call a form called Country. Belonging to the same project. How to call a form ,,country,, that I could use
Public Class Form1
Dim objDS As New DataSet
Dim objDA As New SqlDataAdapter
Public Sqlcon As New SqlConnection With {.connectionString = "server=XXX\MSSQL2008;database=TEST;Trusted_Connection=True;"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If hasConnection() = True Then
MessageBox.Show("uspijesno povezano sa bazom")
End If
getSelc()
End Sub
Public Function hasConnection() As Boolean
Try
Sqlcon.Open()
Sqlcon.Close()
Return True
Catch ex As Exception
MessageBox.Show("Niste povezani sa bazom")
Return False
End Try
End Function
Public Function selc()
Dim objDS = New DataSet
Dim objDA As New SqlDataAdapter
Sqlcon.Close()
Sqlcon.Open()
Dim exCommand As String = ""
Dim myCommand As New SqlCommand
Dim commitTransaction = Sqlcon.BeginTransaction
Try
myCommand = New SqlCommand("EXECUTE " & "regionSelect" & " '" & txtID.EditValue & "', '" & txtShortN.EditValue & "', N'" & txtRegion.EditValue & "', '" & txtStatus.EditValue & "'", Sqlcon)
myCommand.Transaction = commitTransaction
objDA.SelectCommand = myCommand
objDA.Fill(objDS)
commitTransaction.Commit()
Sqlcon.Close()
MessageBox.Show("Podaci su uspijesno poslati")
Catch ex As Exception
MessageBox.Show(ex.Message)
commitTransaction.Rollback()
End Try
End Function
Private Sub SimpleButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
'insert()
End Sub
Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
getSelc()
End Sub
Public Function getSelc()
objDS = New DataSet
Dim com As New SqlCommand
Sqlcon.Close()
Sqlcon.Open()
GridControl1.DataSource = Nothing
Try
com = New SqlCommand("EXECUTE rS '" & txtID.Text & " ' , ' " & txtRegion.Text & "' , '" & txtShortN.Text & "', ' " & txtStatus.Text & " ' ", Sqlcon)
'com = New SqlCommand("SELECT * FROM tblRegion", Sqlcon)
objDA.SelectCommand = com
objDA.Fill(objDS)
com.CommandType = CommandType.StoredProcedure
GridControl1.DataSource = objDS.Tables(0)
objDA.Dispose()
com.Dispose()
Sqlcon.Close()
MessageBox.Show("Im here")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'GridControl1.DataSource = Nothing
'objDS.Tables(0).Rows.Clear()
End Function
Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
getSelc()
Dim newRow As DataRow
newRow = objDS.Tables(0).NewRow
newRow.Item(0) = txtID.EditValue
newRow.Item(1) = txtShortN.EditValue
newRow.Item(2) = txtRegion.EditValue
newRow.Item(3) = txtStatus.EditValue
objDS.Tables(0).Rows.Add(newRow)
End Sub
Private Sub SimpleButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton3.Click
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Country.Show() ' => Is this a good way, and is there any better way and more efficient
End Sub
End Class
You cannot load more than one form on Application Startup. You have to load any one form first then show others from its Form_Load event.
Private Sub StartupForm_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.Show()
End Sub
Or you can load forms manually on Button Click.
Set the Form1 as a StartupForm from the Project Property Window.
Now, Add a button in your first form button1 and write down some code to display another form.
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Dim form2 As New Form2
form2.Show()
End Sub
Another one is calling main method. For that you need to assign Main method in your Project Property Window
Module mainModule
Sub Main()
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.ShowDialog()
End Sub
End Module

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.