Pass Information between 2 Forms - VB.Net - Winforms - vb.net

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.

Related

Datagridview form always open with row in selected state

I have two forms: frmMain and frmProduct
In the main form frmMain, I have a Datagridview1 and the buttons: tsbInsert_click, tsbAlter_click and tsbConsult_click.
When I open the main form frmMain, there is still no row in the Datagridview1 and when I click on any of the tsbAlter_click or tsbConsult_click buttons, the code displays the message "Select a product", which is correct , because there is still no product created in the register.
When I click on the tsbInsert_click button, the code opens the frmProduct to insert a record in the register and then returns to the main form frmMain, which, in the line of the Datagridview1, shows the record that was included.
The problem is that when I include a record in the register, the Datagridview1 ALWAYS returns with the state of the selected row, and the condition If DGProducts.CurrentRow Is Nothing is never true again ... so when I click on tsbAlter_click or tsbConsult_click, the "Select a product" message no longer appears and it should have since I didn't select any rows in Datagridview1.
frmMain Code:
Public Class frmMain
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
End If
End Using
End Sub
Private Sub tsbAlter_Click(sender As Object, e As EventArgs) Handles tsbAlter.Click
If DGProducts.CurrentRow Is Nothing Then
MessageBox.Show("Select a product")
Exit Sub
End If
Dim codProd As String = DGProducts.CurrentRows.Cells("prdCod").Value
Using frm As New frmProduct("Alter", codProd)
frm.ShowDialog()
With DGProducts.Rows(DGProds.CurrentCell.RowIndex)
.Cells("prdCod").Value = Field(0)
.Cells("prdName").Value = Field(1)
.Cells("prdManufac").Value = Field(2)
End With
End Using
End Sub
Private Sub DGProducts_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGProducts.CellEnter
With DGProducts.Rows(DGProducts.CurrentCell.RowIndex)
Campo(0) = .Cells("prdCod").Value
Campo(1) = .Cells("prdName").Value
Campo(2) = .Cells("prdManufac").Value
End With
End Sub
End Class
frmProduct code:
Public Class frmProduct
Private Sub frmProduct_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If _operation = "Alter" Then
txtPrdCod.Text = Campo(0)
txtPrdName.Text = Campo(1)
txtManufct.Text = Campo(2)
Else
txtPrdCod.Text = ""
txtPrdName.Text = ""
txtManufct.Text = ""
Enf If
End Sub
Dim _operation As String
Dim _codProd As String
Public Sub New(operation As String, codProd As String)
InitializeComponent()
Select Case operation
Case "Insert"
_operation = operation
Case "Alter"
_operation = operation
_codProd = codProd
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
Private Sub tsbRecord_Click(sender As Object, e As EventArgs) Handles tsbRecord.Click
Field(0) = txtPrdCod.Text
Field(1) = txtPrdName.Text
Field(2) = txtManufct.Text
Me.Close()
End Sub
End Class
How do I make it so that when I add a product to the register, Datagridview1 DOES NOT return with the line in the SELECTED state and the message "Select a product" appears when I don't select a line from Datagridview1?
The command DGProducts.Rows.Add(Field(0), Field(1), Field(2)), automatically changes the value DGProducts.SelectedRows.Count to 1, so I set DGProducts.CurrentCell = Nothing after command DGProducts.Rows.Add in code:
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
DGProducts.CurrentCell = Nothing
End If
End Using
End Sub

How can user must close all the active form before exiting the application In VB.NET

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.

Prevent users from navigating between tabpages

I created a tabControl and TABpages and I would like to prevent users from navigating between them. I would also like the menu to be visible and the user can't access a tabpage when selecting it from tabcontrol.
I tried to use the remove and Add but in this case the menu disappears and only the tab that I am on appears. I tried to set the enabled property to false and in this case the user can access the tab page but nothing appears which I don't want to happen.
I tried the e.cancel with tabcontrol_selecting event and it worked and the other tabs were locked, but when I tried to navigate between tabpages using the code it did not work. In fact, on the first page, there is a login interface, when the arguments are correct it should take me to the second tabpage, and this did not happen.
I would like to know what I am doing wrong.
This is the code of going from the login tab to the second tab:
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
If Usersel.SelectedIndex = 0 And Password.Text = "0000" Then
TabControl.SelectedIndex = 1
End If
This is the selecting event
Private Sub TabControl_Selecting(sender As Object, e As TabControlCancelEventArgs) Handles TabControl.Selecting, TabControl.SelectedIndexChanged
e.Cancel = False
Dim messageBoxVB As New System.Text.StringBuilder()
messageBoxVB.AppendFormat("{0} = {1}", "TabPage", e.TabPage)
messageBoxVB.AppendLine()
messageBoxVB.AppendFormat("{0} = {1}", "TabPageIndex", e.TabPageIndex)
messageBoxVB.AppendLine()
messageBoxVB.AppendFormat("{0} = {1}", "Action", e.Action)
messageBoxVB.AppendLine()
messageBoxVB.AppendFormat("{0} = {1}", "Cancel", e.Cancel)
messageBoxVB.AppendLine()
MessageBox.Show(messageBoxVB.ToString(), "Selecting Event")
End Sub
This is the menu and how I would like it to be all the time:
Take a look at the following code:
Private isCanceled As Boolean = True
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
If TabControl1.SelectedIndex = 0 And Password.Text = "0000" Then
isCanceled = False
TabControl1.SelectedIndex = 1
End If
End Sub
Private Sub TabControl1_Selecting(sender As Object, e As TabControlCancelEventArgs) Handles TabControl1.Selecting
If e.TabPage.Equals(TabPage2) Then
e.Cancel = isCanceled
End If
End Sub
Only TabControl1.SelectedIndex = 0 and Password.Text = "0000", you can navigate to TabPage2.

Backgroundworker gives multiple error messages

I have a form with three textboxes in it. In my BackgroundWorker1_DoWork handler I test if any TextBox is empty and launch a MessageBox asking the user to fill in all the TextBoxes. This is done in a Try/Catch block. My problem is two fold. If the TextBoxes aren't filled in the user gets the first MessageBox and then another MessageBox when the Catch exception is thrown...so this would be the second MessageBox the user gets. In my BackGroundWorker1_RunWorkCompleted handler I test if an Exception is thrown. It never acknowledges the error and immediately executes the Else block which will be the third message box the user receives saying "Process complete." The Process Complete should not have been shown.
How do I test if there are any TextBoxes not filled in and if they're not throw 1 MessageBox telling the user to fill in all the TextBoxes? And make my RunWorkerComplete handler acknowledge the ElseIf e.Error IsNot Nothing.
Thank you for your help.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Try
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
End If
End If
Next
runProgram()
Catch ex As Exception
MessageBox.Show("An error occured while trying to load this application. Please contact Maxine Hammett for assistance " &
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
ElseIf e.Error IsNot Nothing Then
MsgBox("Error in RunWorkerComplete" & e.Error.Message)
Else
MsgBox(" Process Complete ")
Close()
End If
End Sub
Moved the control checking to the execute button. But now I get errors about the text boxes not having a path (one of the text boxes is a path to folder).
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim launchProgram As Boolean = False
While launchProgram = False
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
launchProgram = False
Else
launchProgram = True
End If
End If
Next
End While
If launchProgram = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I suggest that you check a single text box a time and show the message if its empty:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
Return
Else
cntrl.BackColor = SystemColors.Window
End If
Next
BackgroundWorker1.RunWorkerAsync()
End Sub
Or maybe concatenate the names of the empty text boxes in the For..Each block if you really need to prompt the user this way:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim sb As New StringBuilder
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
If sb.Length > 0 Then sb.Append(", ")
sb.Append(cntrl.Name)
cntrl.BackColor = Color.Yellow
Else
cntrl.BackColor = SystemColors.Window
End If
Next
If sb.Length > 0 Then
MessageBox.Show("Please enter value in all fields on form" & sb.ToString())
Controls.OfType(Of TextBox).Where(Function(a) String.IsNullOrEmpty(a.Text)).FirstOrDefault?.Focus()
Return
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
Otherwise, run the worker.
Good luck.

Close form from second form

My first form is login form, when user correctly log in i am hiding login form and showing up second form. Now instead of hiding login form i want to close it from second form. I thought i will be able to do it but somehow i got troubles with it.
So far i did like this below.
I made interface which my FrmLogin implements:
Public Class FrmLogin
Implements ICloseLogin
Interface:
Public Interface ICloseLogin
Sub Close()
End Interface
FrmLogin implementing interface:
Private Sub ICloseLogin_Close() Implements ICloseLogin.Close
Me.Close()
End Sub
Now i am passing FrmLogin (Me) to second form constructor:
Private Sub ShowMainForm()
Dim FrmMain As New FrmMainMDI(Me)
FrmMain.IsMdiContainer = True
FrmMain.StartPosition = FormStartPosition.CenterScreen
FrmMain.Show()
'Me.Hide() 'not anymore
End Sub
Second form:
Public Class FrmMainMDI
Private closeloginfform As ICloseLogin
Sub New(frmlogin As ICloseLogin)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
closeloginfform = frmlogin
End Sub
Private Sub FrmMainMDI_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
closeloginfform.Close()
End Sub
and when i debug and when it comes to line: closeloginfform.Close() i suppose to see only FrmLogin to be closed, but all is closing somehow. Why?
For further discussion:
Imports DataAccessLayer
Imports FormsUtils
Imports BusinessLayer
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Reflection
Imports System.IO
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports Probix
Public Class FrmLogin
Private Property Form As New FormUtils
Private Property DB As New Procs
Private Property _login As String
Private Property _password As String
Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
CheckAccess()
End Sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub FrmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
DB.OpenConn()
If DB.conn.State = ConnectionState.Open Then
Call Form.InitCombo(CboLogin, "SELECT * from tbLogin", DB.conn, "Login", "Login")
Call Form.InitCombo(CboLanguage, "SELECT * from tbLanguage where Active = 1", DB.conn, "Language", "Id")
Lang.name = DirectCast([Enum].Parse(GetType(Lang.LangShortcut), CboLanguage.GetItemText(CboLanguage.SelectedItem)), Lang.LangShortcut)
Else
Logger.LogIt(Modules.FrmLogin.ToString & ": " & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.SqlServerConnectionError_pl), Application.StartupPath & "\log.txt", False)
Application.Exit()
End If
Catch ex As Exception
Logger.LogIt(ex.tostring)
Application.Exit()
Finally
DB.CloseConn()
End Try
End Sub
Private Sub CheckAccess()
Try
_login = CboLogin.SelectedValue
_password = txtPassword.Text
If Not String.IsNullOrEmpty(txtPassword.Text) And Form.WybranoCombo(CboLogin, "Zaznacz login") Then
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("Select COUNT(*) FROM tbLogin WHERE Login = #Login And Password = #Password", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Login", _login)
cmd.Parameters.AddWithValue("#Password", _password)
con.Open()
Dim o As Integer = cmd.ExecuteScalar()
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
End Using
End Using
Else
MsgBox("Write some password !!")
End If
Catch ex As Exception
Logger.LogIt(Modules.FrmLogin.ToString & ":" & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.Unknown_pl) & " ------> EX-MESSAGE: " & ex.ToString, Application.StartupPath & " \log.txt", False)
Return
End Try
End Sub
Public Sub taskDialog_Opened(sender As Object, e As EventArgs)
Dim taskDialog As TaskDialog = TryCast(sender, TaskDialog)
taskDialog.Icon = taskDialog.Icon
If Not taskDialog.FooterIcon = TaskDialogStandardIcon.None Then
taskDialog.FooterIcon = taskDialog.FooterIcon
End If
taskDialog.InstructionText = taskDialog.InstructionText
End Sub
End Class
Module Program:
Module Program
Public Sub main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New FrmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
Dim FrmMainMDI As New FrmMainMDI()
Application.Run(FrmMain)
End If
End Sub
End Module
Further discussion 2
Solved???: I've added line within CheckAccess() sub, this line:
Me.DialogResult = DialogResult.OK
so this peace of code has been changed only:
...
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
'*************************************
Me.DialogResult = DialogResult.OK '<=========================================
'*************************************
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
...
A less involved way to do this is to start your app from Sub Main and only start the app if the LogIn is correct. For this:
Add a module to your App, and name it Program. Add a Public Sub Main to it
Go to Project Properties and Uncheck Enable Application Framework
Now, for the Startup Object, select "Sub Main"
You can actually name the module anything, "Program" is descriptive and the convention used in C#. Then the Sub Main code:
Public Sub Main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New frmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
frmMain = New MainFrm()
Application.Run(frmMain)
End If
End Sub
Now, your two forms don't even have to know about each other. The MainForm will not even exist if/when the login fails. Whatever overhead there is related to starting/Loading the MainForm is also delayed until (and unless) the log in passes.
Your login button would be something like this (depending on how many failed attempts are allowed):
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
If IsValidUser(tbName.Text, tbPW.Text) Then
DialogResult = Windows.Forms.DialogResult.OK
Else
If tries >= 3 Then
DialogResult = Windows.Forms.DialogResult.Cancel
Else
tries += 1
Exit Sub
End If
End If
Me.Hide()
End Sub