vb.net code to close another form if it is open - vb.net

This is pretty rudimentary, but I can't figure it out.
I want to programmatically close form1 when form2 closes, if form1 is still open. Form2 was opened by a command button on form1.
The code on Form1 that opens Form2 is:
Dim frm As New form2
frm.Show()
What's the best way when Form2 closes to close any open copies of Form1 that are open, also?

If you want to handle your two forms independently, you need to watch over them from a third form or class. So my suggestion would be to create both of them in this third class, and pass a reference of the second form to the first form so it can then open it. This way:
Public Class MyHelper
Public Sub CreateForms()
Dim form2 as New Form2()
AddHandler form2.Closed, AddressOf Form2_OnClosed
‘ Create as many copies as you need
Dim form1 as New Form1(form2)
form1.Show()
End Sub
Protected Sub Form2_OnClosed(sender as object, e as EventArgs)
‘ Same code for each form1 that has been created and opened.
If (form1.IsOpen) Then form1.Close()
End Sub
End Class
Public Class Form1
Private _form2 as Form2
Public Property IsOpen as Boolean = false
Public Sub New(form2 as Form2)
_form2 = form2
End Sub
Protected Sub MyButton_Click(sender as object, e as EventArgs) handles MyButton.Click
‘ You open your form here or wherever you want (even on the constructor)
_form2.Show()
End Sub
Protected Sub Me_OnClosed(sender as object, e as EventArgs) handles Me.Closed
Me.IsOpen = false
End Sub
Protected Sub Me_OnShown(sender as object, e as EventArgs) handles Me.Shown
Me.IsOpen = true
End Sub
End Class

Add this reference to make it work.
Imports System.Linq
If Application.OpenForms().OfType(Of Form1).Any Then
MsgBox("Form1 is open")
End If

Supposing you have 3 forms and want to close the other two on button click
Private Sub EMPLEADOToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EMPLEADOToolStripMenuItem.Click
If Application.OpenForms().OfType(Of BUSCAR_INDEX).Any Then
BUSCAR_INDEX.Close()
ElseIf Application.OpenForms().OfType(Of MIEMBROS_INDEX).Any Then
MIEMBROS_INDEX.Close()
End If
EMP_INDEX.Show()
EMP_INDEX.EmpIDTextBox.Text = EmpIDTextBox.Text
End Sub

Related

(vb.net) how to exit sub when I click button which is in another form?

I'm learning for vb.net step by step. I have two forms and I would like to make a code that is, when I click Button1 which is in the other form, then my main sub exit. I have already searched in google, but I didn't find anything. How can I solve that line?
Public Class Form1
Public Sub Main()
Form2.ShowDialog()
If Form2.Button1_Click = True then '**This line is what I stucked**
Exit Sub
End if
End Sub
End Class
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
An example using DialogResult.
In Form1:
If Form2.ShowDialog = DialogResult.OK Then
' ... do something in here ...
End If
In Form2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.DialogResult = DialogResult.OK
End Sub
Note that if the user cancels the Form2 dialog without hitting the button then you'll get a result of Cancel back instead.

How can I refresh One Form when other Form is closed VB.NET

I want to refresh Form1 when Form2 is closed,
I have searched a lot but none of those queries answered my question.
I want to detect the Form2 closing event in Form1.
Why not refresh Form1 in the Closed event of Form2?
Private Sub Form2_Closed(sender As Object, e As EventArgs) Handles Me.Closed
Form1.Refresh()
End Sub
You must have an instance of Form2, and you AddHandler to subscribe to its Closed event.
I don't know how you create your Form2. So here is a solution which should work in your case. Just replace _myForm2 = New Form2() with however yours is created
Public Class Form1
Public ReadOnly Property MyForm2 As Form2
Get
Static _myForm2 As Form2
If _myForm2 Is Nothing Then
_myForm2 = New Form2() ' replace with how your Form2 is created
End If
Return _myForm2
End Get
End Property
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler MyForm2.FormClosed, AddressOf myForm2_Closed ' add event handler
MyForm2.Show()
End Sub
Private Sub myForm2_Closed(sender As Object, e As FormClosedEventArgs)
Me.Refresh()
End Sub
End Class
If you are using a default Form2 instance, you shouldn't be. But if you must, you would use _myForm2 = Form2

How to check if a Form has focus?

I have two WinForms. Let's say MainForm and ChildForm.
What I'm trying to make is when the MainForm is activated the ChildForm should always be visible, and when the MainForm loses focus the ChildForm should be hidden except if it's the ChildForm which was activated.
Here is my code :
AddHandler Me.MainForm.Activated, Sub()
Me.ChildForm.Show()
End Sub
AddHandler Me.MainForm.Deactivate, Sub()
If Not Me.ChildForm.Focused Then
Me.ChildForm.Hide()
End If
End Sub
AddHandler Me.ChildForm.Deactivate, Sub()
If Not MainForm.Focused Then
Me.ChildForm.Hide()
End If
End Sub
The code doesn't work. Basically when I click on a certain form (on the child form for example), the property Me.ChildForm.Focused is not correct and then ChildForm is hidden while it should be visible.
Can anyone know how to achieve that please ?
Not sure if this is a good one, but the idea is using flags for MainForm and ChildForm active status. These flags are set when MainForm and ChildForm's Activated and Deactive events are fired. For simplicity, I'll use a module to store the flags and the instance of ChildForm. Then call SetChildVisible() method in MainForm, Form1 and Form2 Activated event. Set startup object to MainForm.
Module1
Module Module1
Public FChild As ChildForm
Public FMainActive As Boolean
Public FChildActive As Boolean
Public Sub SetChildVisible()
FChild.Visible = Not FChildActive And FMainActive
End Sub
End Module
MainForm
Public Class MainForm
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim f1 = New Form1
Dim f2 = New Form2
Dim child = New ChildForm
Module1.FChild = child
child.Show()
f1.Show()
f2.Show()
End Sub
Private Sub MainForm_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
Module1.FMainActive = True
Module1.SetChildVisible()
End Sub
Private Sub MainForm_Deactivate(sender As Object, e As EventArgs) Handles MyBase.Deactivate
Module1.FMainActive = False
End Sub
End Class
ChildForm
Public Class ChildForm
Private Sub ChildForm_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
Module1.FChildActive = True
End Sub
Private Sub ChildForm_Deactivate(sender As Object, e As EventArgs) Handles MyBase.Deactivate
Module1.FChildActive = False
End Sub
End Class
Form1
Public Class Form1
Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
Module1.SetChildVisible()
End Sub
End Class
Form2
Public Class Form2
Private Sub Form2_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
Module1.SetChildVisible()
End Sub
End Class

Reset form with original state

I would like to reset my form using vb.net i would try to below code but form is close can't open new form.
Private Sub resert_button_Click(sender As Object, e As EventArgs) Handles resert_button.Click
Dim client = New client_entry
client.Show()
Me.Close()
End Sub
Try Me.Hide and swap the order
Me.Hide()
client.Show()
There could be multiple ways to handle this one but myapproach would be like calling form_shown even where I will load required data and during reset i will call this event.
Private Sub Me_Shown(sender As Object, e As EventArgs) Handles Me.Shown
LoadData() 'This function/sub will load data for this form
End Sub
Private Sub resert_button_Click(sender As Object, e As EventArgs) Handles resert_button.Click
Me_Shown(sender,e)
End Sub
Use Me.Dispose() instead of Me.Close() it will dispose the form then when you call it again Yourform.Show(), It will Generate a new one.
One way of doing this would be to add a property to Form2. I'm assuming that you have two forms Lets call them Form1 and Form2. Somewhere in the code for Form1, you declare an instance of Form2 ..
Dim frm2 As New Form2
and at some point you want to show Form2 as a modal window ..
frm2.ShowDialog()
For the moment lets look at the Form2 code
I'm assuming here that you have a button to reset the form and to close the form, you just click on the form close button in the top right hand corner and maybe you have a button to close the form as well. Consider the following code for Form2
Public Class Form2
Friend Property resetOnClose As Boolean = False
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
resetOnClose = True
Me.Hide()
End Sub
Private Sub btnclose_Click(sender As Object, e As EventArgs) Handles btnclose.Click
resetOnClose = False
Me.Hide()
End Sub
End Class
There is a property called resetOnclose which is a Boolean type. If you click on the reset button, this property is set to True If you click on the close button, the resetOnClose property is set to false.
In all these bits of code, frm2 is Hidden - not closed. This means that the form and its resetOnclose property is still available to Form1. OK now to look at the Form1 code ..
Public Class Form1
Dim frm2 As New Form2
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
frm2.ShowDialog()
Do
If frm2.resetOnClose Then
frm2.Close()
frm2 = New Form2
frm2.ShowDialog()
Else
frm2.Close()
End If
Loop Until frm2.resetOnClose = False
End Sub
End Class
For this example, frm2 is opened as soon as Form1 is shown, but you can put the relevant code anywhere you need
In the Form1.Shown code you will see a loop. The loop will continue looping as long as resetOnClose is True. When frm1 is shown modally, execution in this Form1 code waits until frm2 is hidden or closed. Next, the Form1 code checks to see if the resetOnClose property is true or false. If it's false, frm2 is closed and the loop terminates. If the property is true, frm2 is closed and reassigned a new instance of Form2 in its default state.
Voila!

Changing Controls of a form inside a panel

I am facing a weird problem
I have 3 forms: MainForm, Form1, Form2
MainForm has 1 Panel: Panel1
Form1 has 1 Label: NameLbl and Button: ChangeBtn
Form2 has 1 textbox: NameTxt and Button: SaveBtn
I used the following code to open form1 inside Panel1 in mainform
Panel1.Controls.Clear()
Dim FormInPanel As New Form1()
FormInPanel.TopLevel = False
Panel1.Controls.Add(FormInPanel)
FormInPanel.Show()
On ChangeBtn.Click Form2 opens as showdialog
I want NameLbl.text to change to NameLbl.text when SaveBtn is clicked But normal code doesnt work.
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Form1.NameLbl.text=NameTxt.text
End Sub
What Should I do? Any suggestions? Given that i need to open the forms in panels for certain reasons.
Please keep in mind that this is just an example. I have multiple controls in Form1 which i want to change on form2.SaveBtn.click
I have also tried this but it does nothing
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
For Each c As Control In MainForm.Panel1.Controls(0).Controls
If c.Name="NameLbl" Then
c.Text = NameTxt.Text
End If
Next
End Sub
Please Somebody tell me how it do it!
Form2 doesn't seem to have any connection back to Form1 or MainForm. You'd need to raise an event from Form2 which MainForm handles or another class handles and can pass to MainForm
Edit:
Sorry, I've just seen how you're calling Form2. There are lots of ways to get a value back from Form2 after calling ShowDialog(). One is to create a property called Result and check Result if ShowDialog() == DialogResult.OK. Something like the following.
Public Class Form2
Inherits System.Windows.Forms.Form
Public Property Result() As String
Get
Return m_Result
End Get
Set
m_Result = Value
End Set
End Property
Private m_Result As String
End Class
Public Class Form1
Inherits System.Windows.Forms.Form
Public ChangeBtn As Button
Public NameLbl As Label
Public Sub New()
Me.ChangeBtn = New Button()
AddHandler Me.ChangeBtn.Click, AddressOf ChangeBtn_Click
Me.NameLbl = New Label()
End Sub
Private Sub ChangeBtn_Click(sender As Object, e As EventArgs)
Dim form As New Form2()
Dim dr = New form.ShowDialog()
If dr = DialogResult.OK Then
Me.NameLbl.Text = form.Result
End If
End Sub
End Class
I'd like to add that if you plan on growing this application much larger you'll run into issues with maintenance. Look into some patterns for dealing with UI logic like MVC, MVP, MVVM if you're interested.
you can try this code:
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
panel1.Controls(0).NameLbl.text=NameTxt.text '"0" is the index of forminpanel in panel1,maybe it need to change.
End Sub
Form1 is contained in Panel1, so you can not access it via
Form1.
Only MainForm is visible from Form2:
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
For Each c As Control In MainForm.Panel1.Controls(0).Controls
If TypeOf c Is TextBox Then
c.Text = NameTxt.Text
End If
Next
End Sub
Try this:
For Each form1 As Form1 In MainForm.OwnedForms.OfType(Of Form1)
Form1.NameLbl.text = NameTxt.text
Next
I've faced same issue and I've fixed with this
Dim f As FormInPanel
f = Form.Panel1.Controls(0)
f.transection = True
f.NameLbl.text=NameTxt.text