Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Call validation()
    Select Case valid
        Case False
            Exit Sub
    End Select


    Try

        Dim FileSize As UInteger
        Dim mstream As New System.IO.MemoryStream
        PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
        Dim arrImage() As Byte = mstream.GetBuffer()
        FileSize = mstream.Length
        mstream.Close()

        sqlString = "INSERT INTO tbladminaccount(accname,accposition,accage,accaddress,accpassword,accgender,Acc_pix) VALUES(@field1,@field2,@field3,@field4,@field5,@field6,@urlimage)"
        objCommand = New MySql.Data.MySqlClient.MySqlCommand(sqlString, objConn)
        With objCommand
            .Parameters.AddWithValue("@field1", firstNameTextBox.Text)
            .Parameters.AddWithValue("@field2", positionComboBox.Text)
            .Parameters.AddWithValue("@field3", ageTextBox.Text)
            .Parameters.AddWithValue("@field4", addressTextBox.Text)
            .Parameters.AddWithValue("@field5", passwordTextBox.Text)
            .Parameters.AddWithValue("@field6", genderComboBox.Text)
            .Parameters.AddWithValue("@urlimage", arrImage)
        End With
        objCommand.ExecuteNonQuery()
        objCommand.Dispose()
        objDreader.Close()
        MessageBox.Show("Account Added!", "Warehouse Monitoring", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Call fillAccountListView()
        Call clearAllfields()
        Call disableAllFields()
        Button2.Enabled = False
        Button1.Enabled = True
        Button3.Enabled = False
        Button4.Enabled = False
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Warehouse Monitoring", MessageBoxButtons.OK, MessageBoxIcon.Stop)
    End Try
End Sub

You don't want all that code inside a button click event handler.

Break your code up into discrete classes and methods of specific functionality. It will make everything much easier.

Your button click code should be very simple like below - note this is pseudo code (http://en.wikipedia.org/wiki/Pseudocode)

If FormIsValid() Then
    If UserExists() Then
        ShowUserExistsMessage()
    Else
        SavePicture()
        SaveRecord()
        ClearForm()
    End If
Else
    ShowInvalidFormMessage()
End If

So you can write a Function which returns a bool if a user exists. Try and think like this rather than having one massive block of code which does everything. It will be easier, more fun, easier to fix and add to later and easier for other people to understand and easier to reuse code too.

Edited 1 Year Ago by DaveAmour: typo

Comments
Always worth pointing out.
Great advice!
This article has been dead for over six months. Start a new discussion instead.