0

良い一日、

私は非常に奇妙な出来事を経験しています。キーボードの ENTER ボタンを押すたびに、テキスト ボックスの KeyDown イベントが発生し、対応するコードが実行されることを期待しています。代わりに、フォームが消えます (あたかも .Hide() メソッドが呼び出されたかのように)。デバッグすると、KeyDown イベントが発生した後に実行されるはずのコードが適切に実行されていることがわかりますが、フォームが消えてしまいます。

これまでに遭遇したことがないので、どうすればよいかわかりません。どんな助けでも大歓迎です。ありがとう。

私のフォームのコードは次のとおりです。

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
4

2 に答える 2

1

次の方法でフォームが消える問題は解決しない可能性がありますが、下流の問題は解決します。

GetDBData() では、accountNumber を TextBoxAcount.Text の値に割り当てています。これは、習慣になればなるほど強く推奨されるパラメーターを使用しない限り、引用符で囲む必要があります。

Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)

パラメーターには、暗黙的な型変換、インジェクション攻撃の防止など、多くの利点があり、予期しない動作を修正することさえあります。

于 2012-10-12T16:45:56.063 に答える
0

私は問題を理解しました。GetDBData() 関数の最後で Dispose() を呼び出していたので、実行が TextBox に戻る前にフォームが破棄されていました。私はそれを削除し、すべてが再びうまくいきました。

于 2012-10-12T17:01:46.187 に答える