Here's my code
Private Sub BookButton_Click(sender As Object, e As EventArgs) Handles BookButton.Click
Dim Response = InputBox("Enter Employee ID", "Employee Confirmation", "Employee ID", 500, 700)
If Response = "EmployeeTest" Then
Form2.Show()
Else
MsgBox("Invalid Employee ID, Please Try Again", MsgBoxStyle.Exclamation, "Invalid input")
End If
End Sub
when i run the project, after the I entered the correct input, its back to Form1, nothing happens, the input box closed itself. I want to show Form2 after user entered the correct input
Related
I have 2 Forms in a Product Registration Project
The 1st form has 3 buttons: New | Consult | Change | - that call the 2nd Form where I have a Photo Button.
New Button:
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Consult Button:
Private Sub tsbConsult_Click(sender As Object, e As EventArgs) Handles tsbConsult.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.txtDes.Enabled = False
frm.txtDesRed.Enabled = False
frm.ShowDialog()
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
End Sub
Change Button
Private Sub tsbChange_Click(sender As Object, e As EventArgs) Handles tsbChange.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
In the 2nd Form, the Photo button will have two different behaviors:
when the user has clicked on the "New" button on Form 1, the code will open a search screen for the user to select an image in a folder on the Photos in server and show it in the picturebox1 in Form 2;
when the user has clicked on the "Consult" or "Change" button on Form 1, the code will make a comparison between the prdCod field of the Products Table and the filename of the image in the Photos folder and, when found, will show the image in the picturebox1 in Form 2.
If the "clicked button" on form 1 is "New", do the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Using open As New OpenFileDialog With {
.Title = "Select Photo",
.FileName = "",
.Filter = "Images PNG,JPEG,BMP,JPG|*.png;*.jpeg";*.bmp;*.jpg,
.Multiselect = False}
If open.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(open.FileName)
End If
End Using
End Sub
If the "clicked button" on form 1 is "Consult or Change", execute the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Dim IdProduto As String = prdCod ***field Products Table that will be used for the search in the Photos folder
If File.Exists("\\server\cmg\projects\Photos" & IdProduto) Then ***Search the image from the Photos folder on the server
PictureBox1.Image = Image.FromFile("\\server\cmg\projects\Photos" & IdProduto)
End If
End Sub
How do I check which button was clicked on the 1st form to be able to perform the correct Private Sub on the 2nd form?
It worked:
In the first form (frmConsProd), in the New Button code (tsbNew_Click), I include the parameter that will be sent to
the second form (frmCadProd):
Public Class frmConsProd
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frmCadProd("New")
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
In the second form (frmCadProd) I created a class variable (_operation) and the constructor (Public Sub New) to receive the sent parameter:
Public Class frmCadProd
Dim _operation As String
Public Sub New(operation As String)
InitializeComponente()
Select Case operation.ToLower()
Case "new"
_operation = operation
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
End Class
Thanks to Messrs. #F0r3v3r-A-N00b, #jmcilhinney e #user09938, for the help.
I have 4 Form
Form Menu
Form Login
Form Program1
Form Program2
I want before closing the application i must close all the active form. Or something like i need to logout first before closing the app is fine too
ps : sorry for my explanation hope someone can help me
To Login I use module
Module Module1
#Region "Login"
Public Sub logins()
MenuUtama.ProgramAplikasiToolStripMenuItem.Enabled = True
MenuUtama.ProgramSedehana1ToolStripMenuItem.Enabled = True
MenuUtama.ProgramSederhana2ToolStripMenuItem.Enabled = True
MenuUtama.LogoutToolStripMenuItem.Enabled = True
MenuUtama.LoginToolStripMenuItem.Enabled = False
End Sub
#End Region
#Region "Logout"
Public Sub logouts()
MenuUtama.ProgramAplikasiToolStripMenuItem.Enabled = False
MenuUtama.ProgramSedehana1ToolStripMenuItem.Enabled = False
MenuUtama.ProgramSederhana2ToolStripMenuItem.Enabled = False
MenuUtama.LogoutToolStripMenuItem.Enabled = False
MenuUtama.LoginToolStripMenuItem.Enabled = True
End Sub
#End Region
End Module
To Call Login From the module
Private Sub validation()
If txtusername.Text = "" Or txtpassword.Text = "" Then
MsgBox("Input Your Username or password", MsgBoxStyle.Exclamation)
ElseIf txtusername.Text = "user" And txtpassword.Text = "password" Then
MsgBox("Login Succses", MsgBoxStyle.MsgBoxRight)
logins()
Me.Close()
Else MsgBox("Wrong Password", MsgBoxStyle.Exclamation)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
validation()
End Sub
Code in Form Menu
Private Sub close()
Dim result As DialogResult = MsgBox("You sure want to close the app?", MsgBoxStyle.OkCancel)
If result = DialogResult.OK Then
Me.Close()
Else
Return
End If
End Sub
Private Sub KeluarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KeluarToolStripMenuItem.Click
close()
End Sub
What i want is, if a Form is active, and i close the application, Then come massage to inform the user that he need to close all the active form first.
For now i use this to inform if user want to exit the application
I would recommend that you catch either the Closed or Closing event from Form Menu (Open the Form code, select Form events, then in the next box to the right select either closed or closing)
You'll have a new section of code like this:
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
End Sub
Then in the middle of that new Sub, you can type something like:
If Login.visible then
msgbox("you need to close the Login form")
End If
Also note that if you make your second, third and fourth windows modal, then the user will HAVE to close them before ending up back at the Main window.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
MsgBox()
Input("Are you an employee or a customer: ")
If Name = "employee" Then
Name = Input("first 2 letters of first name:")
Dim number As Object
number = input(str("Year enter of company exc 20: "))
ElIf Name = "customer" Then
Name = Input("Enter email: ")
Dim password As Object
password = Input("Enter password: ")
Dim username As String
username = Name
Else
Print("Incorrect. Try again.")
End If
End Sub
This code is to make a login on visual basic using the button tool so it can go to another page
Why would you create a desktop application and not leverage any of the controls? You would be better off creating a form that has:
Two RadioButtons to distinguish login type
Two TextBox controls
One NumericUpDown control
When the user changes their login type selection, it would dynamically hide/show one of the TextBox controls and the NumericUpDown control. Take a look at this screenshot:
Now in the RadioButton's CheckedChanged event, you would change the label's text and toggle the visibility of the controls:
Private Sub RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged
Label1.Text = If(RadioButton1.Checked, "Email", "First 2 letters of first name")
TextBox1.Text = String.Empty
TextBox2.MaxLength = If(RadioButton1.Checked, Integer.MaxValue, 2)
TextBox2.Text = String.Empty
TextBox2.Visible = RadioButton1.Checked
Label2.Visible = RadioButton1.Checked
NumericUpDown1.Visible = RadioButton2.Checked
Label3.Visible = RadioButton2.Checked
End Sub
Finally, when the user clicks on login you can get the values based on the login type using the NumericUpDown to get a numeric value:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If (RadioButton1.Checked) Then
' customer login
Dim customerName = TextBox1.Text
Dim password = TextBox2.Text
Else
' employee login
Dim employeeName = TextBox1.Text
Dim number = Decimal.ToInt32(NumericUpDown1.Value)
End If
End Sub
I am working on an employee database and am having issues with my TRY\CATCH for saving records as it pertains to exception handling. The issue I am experiencing is that it will run the TRY and ignore the CATCH, allowing invalid data to pass and save to the file. I am very new to visual basic and am unsure of why this is not working. Here is my code for the form:
Option Strict Off
Imports System.IO
Public Class frmEmployeeData
'Variable Declarations
Dim BlnisChanged As Boolean = False
Dim empFirstName As String
Dim empMiddleName As String
Dim empLastName As String
Dim empNumber As Integer
Dim empDepartment As String
Dim empTelephone As String
Dim empExtension As Integer
Dim empEmailAddress As String
Dim empSelection As String
Dim fileName As String
Dim intTryParse As Integer = 0
Private Sub frmEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Adds the department options to the combo box dropdown list
ComboBoxEmpDepartment.Items.Add("Accounting")
ComboBoxEmpDepartment.Items.Add("Administration")
ComboBoxEmpDepartment.Items.Add("Marketing")
ComboBoxEmpDepartment.Items.Add("MIS")
ComboBoxEmpDepartment.Items.Add("Sales")
End Sub
Sub ClearItems()
'Clears text boxes
txtFirstName.Clear()
txtMiddleName.Clear()
txtLastName.Clear()
txtEmployeeNumber.Clear()
ComboBoxEmpDepartment.ResetText()
txtTelephone.Clear()
txtExtension.Clear()
txtEmailAddress.Clear()
End Sub
Sub SaveItems()
Dim savedEmployeeFile As StreamWriter
Try
'Creates the employee file
savedEmployeeFile = File.CreateText(fileName)
'writes information entered by user into file
savedEmployeeFile.WriteLine(txtFirstName.Text)
savedEmployeeFile.WriteLine(txtMiddleName.Text)
savedEmployeeFile.WriteLine(txtLastName.Text)
savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
savedEmployeeFile.WriteLine(txtTelephone.Text)
savedEmployeeFile.WriteLine(txtExtension.Text)
savedEmployeeFile.WriteLine(txtEmailAddress.Text)
'Closes the file
savedEmployeeFile.Close()
BlnisChanged = False
'Clears the text boxes
ClearItems()
Catch ex As Exception
'Throws error if file could Not be created
MessageBox.Show("Unable To Create File. Please Try Again", "Error In Saving")
End Try
End Sub
Sub AppendToFile()
Dim savedEmployeeFile As StreamWriter
Try
'append to file
savedEmployeeFile = File.AppendText(fileName)
'writes information entered by user into file
savedEmployeeFile.WriteLine(txtFirstName.Text)
savedEmployeeFile.WriteLine(txtMiddleName.Text)
savedEmployeeFile.WriteLine(txtLastName.Text)
savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
savedEmployeeFile.WriteLine(txtTelephone.Text)
savedEmployeeFile.WriteLine(txtExtension.Text)
savedEmployeeFile.WriteLine(txtEmailAddress.Text)
MessageBox.Show("Employee saved successfully.", "Success")
'Closes the file
savedEmployeeFile.Close()
BlnisChanged = False
'Clears the text boxes
ClearItems()
Catch ex As Exception
MessageBox.Show("No file exists. Please select 'Save As' Option.", "Error In Saving")
End Try
End Sub
Private Sub btnSaveRecord_Click(sender As Object, e As EventArgs) Handles btnSaveRecord.Click
Dim savedEmployeeFile As StreamWriter
'EXCEPTION HANDLING
'verifies first name field content
If txtFirstName.Text = "" Then
MessageBox.Show("First name cannot be blank", "Invalid Entry")
End If
'verifies middle name field content
If txtMiddleName.Text = "" Then
MessageBox.Show("Middle name cannot be blank", "Invalid Entry")
End If
'verifies last name field content
If txtLastName.Text = "" Then
MessageBox.Show("Last name cannot be blank", "Invalid Entry")
End If
'verifies employee number field content
If txtEmployeeNumber.Text = "" Then
MessageBox.Show("Employee number cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
MessageBox.Show("Employee number must be numeric", "Invalid Entry")
ElseIf CStr(txtEmployeeNumber.Text) < 0 Then
MessageBox.Show("Employee number must be positive", "Invalid Entry")
End If
'verifies department field content
If ComboBoxEmpDepartment.Text = "" Then
MessageBox.Show("Employee department cannot be blank", "Invalid Entry")
End If
'verifies telephone number field content
If txtTelephone.Text = "" Then
MessageBox.Show("Telephone number cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
MessageBox.Show("Telephone number must be numeric", "Invalid Entry")
End If
'verifies extension field content
If txtExtension.Text = "" Then
MessageBox.Show("Extension cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtExtension.Text, intTryParse)) Then
MessageBox.Show("Extension must be numeric", "Invalid Entry")
ElseIf CInt(txtExtension.Text) < 0 Then
MessageBox.Show("Extension must be positive", "Invalid Entry")
End If
'verifies email address field content
If txtEmailAddress.Text = "" Then
MessageBox.Show("Email Address cannot be blank", "Invalid Entry")
End If
'If no filename exists, will prompt save dialog box and prompt user to save as
If fileName = String.Empty Then
If sfdSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
fileName = sfdSave.FileName
SaveItems()
End If
'If filename exists, append item to file
Else
AppendToFile()
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clears all content currently within text boxes
txtFirstName.Clear()
txtMiddleName.Clear()
txtLastName.Clear()
txtEmployeeNumber.Clear()
ComboBoxEmpDepartment.ResetText()
txtTelephone.Clear()
txtExtension.Clear()
txtEmailAddress.Clear()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Closes Program
frmUserSelection.Show()
Me.Visible = False
End Sub
Private Sub SaveFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles sfdSave.FileOk
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
'Picture Obtained From:
'"User Add Icon-Shine Set: Add New User, Add User." Free Icons PNG. Accessed 14 October 2018. https://www.freeiconspng.com/img/2487
End Sub
End Class
A Catch block only executes if an exception is thrown from within the Try block. I don't see anything here which would cause that to happen. It appears as though you're misunderstanding this a bit.
Don't put validation logic in a Catch block. All that should go there is code to handle an exception if one occurs. For example, if the connection to a database fails because the database itself is offline, or if writing to a file fails because the file can't be found/opened.
Put your validation logic before you even make the attempt to save it. If the user input fails validation, don't attempt to save it. Instead, return an error to the user. Only if your custom validation passes would you then begin the Try, write to your data store, and handle an exception if one occurs.
net gurus
I have the following piece of code. If I mouse click on the messagebox OK button the code behaves correctly but if I press enter it sets focus back to txtusename but then jumps to txtpassword. Any ideas why?
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If String.IsNullOrEmpty(txtUserName.Text) Then
Dim msgResult As DialogResult = MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
If msgResult = DialogResult.OK Then
txtUserName.Focus()
End If
Return
ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
Dim msgResult As DialogResult = MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
'MsgBox("Password required", vbOKOnly, vbExclamation)
txtUserName.Select()
txtPassword.Select()
Return
End If
In case there is a value on txtUserName and the txtPassword is null or empty you show a MessageBox. After showing the MessageBox (no matter the user selected) you select the txtUserName and txtPassword. Since you can only select one TextBox, the txtPassword is finally selected.
On the Form the txtUserName is selected first, so the cursor jumps from txtPassword to txtUserName. At the end the txtPassword is selected so the cursor jumps now from txtUserName to txtPassword.
You also using .Select on the ElseIf part. In case you want to set the cursor to the TextBox you need to use .Focus (like on the If part).
You need to remove the txtUserName.Select() on the ElseIf and using .Focus instead of .Select on txtPassword to solve your issue:
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If String.IsNullOrEmpty(txtUserName.Text) Then
MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
txtUserName.Focus()
Return
ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
txtPassword.Focus()
Return
End If
'more code for database connection.
End Sub