Form2 won't close and if I close it form1 will close as well. vb.net - vb.net

So I made this game in vb.net, and when you run it, it will ask you for a name, that's form2. The thing is, when you put a name, form2 will not close/disappear, and if you close it the whole game will close.
This is the code for form2:
Public Class Form2
Public Shared myMoney As Long
Public Shared welcome As String
Private Sub PositronButton1_Click(sender As Object, e As EventArgs) Handles PositronButton1.Click
Form1.welcome = txtName.Text
Form1.lblWelkom.Text = "Welcome," & " " & Form1.welcome
MsgBox("Welcome," & " " & Form1.welcome & "." & "You recieved 500 money.")
Form1.myMoney = 500
Form1.lblMoney.Text = Form1.myMoney
Form1.Show()
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TopMost = True
End Sub
End Class

It seems you have wrong settings in your project.
Go to "Project", "Settings" and then have a look after "Shutdown mode".
Yours is probably set to "When last form closes". But you have to set "start form".
Also do not use Form1.Show because this is wrong, create an instance of it, then call it.
Dim frm As New Form1
frm.Show()
Also use ShowDialog for showing the Form2, it returns a DialogResult, and if it is "OK", you can close the form.

Firstly, instead of setting Me.TopMost on the load event, you should call Form2.Focus() when you first open the Form in your Form1 code.
Secondly I am not sure how you are opening Form2, I assume you are using ShowDialog() In that case, in order to close Form2, you should call Me.DialogResult = DialogResult.OK
Hope it Helps

Related

Form3 linked to Form2. Values not updating upon change

i am creating a windows forms app with 3 forms.
I am able to send values and update them timely between form1 and form2.
But i have problems with updating values from form3 to form2.
My code in form2 is as follows:
Public Sub GetValues_Form3()
xlExcelLink = Form3.LoadProjDB()
If xlExcelLink Is Nothing Then
MsgBox("Projekt Datenbank fehlt." & vbNewLine & "Bitte wählen Sie in den Optionen erneut die Projektdatenbank aus.", , "Fehler")
Form1.ib_OptionsTab_Click(Form1.ib_OptionsTab, Nothing) 'Opens Form3
End If
End Sub
My code in Form 3 is as follows:
Private Sub ib_ProjDB_Browse_Click(sender As Object, e As EventArgs) Handles ib_ProjDB_Browse.Click
If OpenFileDialog1.ShowDialog() <> DialogResult.Cancel Then
tb_Excel.Text = OpenFileDialog1.FileName
End If
End Sub
Function LoadProjDB() As String
Dim Form3_ExcelPath As String = tb_Excel.Text
MsgBox(Form3_ExcelPath)
If Form3_ExcelPath IsNot Nothing And System.IO.File.Exists(Form3_ExcelPath) Then
MsgBox(Form3_ExcelPath)
Form2.Label1.Text = Form3_ExcelPath
Return Form3_ExcelPath
Else
Return Nothing
End If
End Function
I have a default file path. I check if the path exists.
If it doesnt exist, i want my form2 to open form3, where i can select the new file.
After form3 is closed, i get the path string from form3 in form2, and it checks if the string is nothing.
If it is nothing, it will open form3 again.
The problem here is:
I am able to select a new file and it is displaying correctly in form3.
But form2 is not updating its vale from form3.
It still has the first value that it got from form3.
Please help.
Thank you.
Edit1:
Now I am trying to run Subs and Function in Form2 from Form1.
It seems the variables are changing temporarily when executed, but the functions are not being triggered by my action.
I cant seem to find a solution for it till now.
Edit 2:
#Idle_Mind
Im using a public sub which handles button click in form1 to display form3.
Public Sub ib_OptionsTab_Click(sender As Object, e As EventArgs) Handles ib_OptionsTab.Click
If ib_OptionsTab.Tag = 0 Then
Form3_in_Panel()
ElseIf ib_OptionsTab.Tag = 1 Then
Form3_Out_Panel()
End If
End Sub
Form3 is the oped using this function in form1.
Function Form3_in_Panel()
If Form3_Load = True Then
Dim f3 As New Form3
f3.TopLevel = False
f3.Dock = DockStyle.Fill
pnl_Fill.Controls.Add(f3)
f3.Visible = True
f3.BringToFront()
Form3_Load = False
frm3 = pnl_Fill.Controls.Item("Form3")
Else
pnl_Fill.Controls.Item("Form3").Visible = True
End If
ib_OptionsTab.Tag = 1
Return Nothing
End Function

Closing parent form when child form also closes

Aside from my main form I have another form, frmAddFixture, which can open frmAddReport.
I'm simply trying to close frmAddFixture when "No" is selected from the msgbox, which also closes (successfully) Me (frmAddReport). If "Yes" is selected frmAddFixture should stay open, which it does. But I can't get it to close for "No". I've tried adding my own handler in to detect when frmAddReport is closing, but I couldn't get that working.
frmAddReport Code (run after a "Submit" button has been clicked):
Private Sub showMsg()
Select Case MsgBox("Do you want to add another player report for this fixture?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Add further reports")
Case MsgBoxResult.Yes
isNewFixture = False
Me.Close()
Case MsgBoxResult.No
isNewFixture = True
Me.Close()
''Close frmAddFixture
'frmAddFixture.Dispose()
'frmAddFixture.Close()
'frmAddFixture.Hide()
End Select
End Sub
Attempted:
Private Sub frmAddReport_FormClosed(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.FormClosed
frmAddFixture.Dispose()
End Sub
Here is what I think you are trying to do.
Let's ignore the message box for a moment and say that we have two forms : Form1 and Form2. We want that as soon as Form2 is colsed, Form1 will be disposed (closed) as well. I'ts pretty simeple :
Public Class Form2
' Occurs when Form2 is closed (note the event handler).
Private Sub Form2_FormClosed(sender As Object, e As EventArgs) Handles MyBase.FormClosed
Form1.Dispose()
End Sub
End Class

How to call a Sub without knowing which form is loaded into panel?

On every DataGridView1_SelectionChanged event I need to run a Private Sub OnSelectionChanged() of the form that is loaded into Panel1 (see the image http://tinypic.com/r/2nu2wx/8).
Every form that can be loaded into Panel1 has the same Private Sub OnSelectionChanged() that initiates all the necessary calculations. For instance, I can load a form that calculates temperatures or I can load a form that calculates voltages. If different element is selected in the main form’s DataGridView1, either temperatures or voltages should be recalculated.
The problem is - there are many forms that can be loaded into Panel1, and I’m struggling to raise an event that would fire only once and would run the necessary Sub only in the loaded form.
Currently I’m using Shared Event:
'Main form (Form1).
Shared Event event_UpdateLoadedForm(ByVal frm_name As String)
'This is how I load forms into a panel (in this case frm_SCT).
Private Sub mnu_SCT_Click(sender As Object, e As EventArgs) Handles mnu_SCT.Click
frm_SCT.TopLevel = False
frm_SCT.Dock = DockStyle.Fill
Panel1.Controls.Add(frm_SCT)
frm_SCT.Show()
Var._loadedForm = frm_SCT.Name
RaiseEvent event_UpdateLoadedForm(Var._loadedForm)
End Sub
‘Form that is loaded into panel (Form2 or Form3 or Form4...).
Private WithEvents myEvent As New Form1
Private Sub OnEvent(ByVal frm_name As String) Handles myEvent.event_UpdateLoadedForm
‘Avoid executing code for the form that is not loaded.
If frm_name <> Me.Name Then Exit Sub
End Sub
This approach is working but I’m sure it can be done way better (I'd be thankful for any suggestions). I have tried to raise an event in the main form like this:
Public Event MyEvent As EventHandler
Protected Overridable Sub OnChange(e As EventArgs)
RaiseEvent MyEvent(Me, e)
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) _
Handles DataGridView1.SelectionChanged
OnChange(EventArgs.Empty)
End Sub
but I don't know to subscribe to it in the loaded form.
Thank you.
Taking into account Hans Passant’s comments as well as code he posted in related thread I achieved what I wanted (see the code below).
Public Interface IOnEvent
Sub OnSelectionChange()
End Interface
Public Class Form1
' ???
Private myInterface As IOnEvent = Nothing
' Create and load form.
Private Sub DisplayForm(frm_Name As String)
' Exit if the form is already displayed.
If Panel1.Controls.Count > 0 AndAlso _
Panel1.Controls(0).GetType().Name = frm_Name Then Exit Sub
' Dispose previous form.
Do While Panel1.Controls.Count > 0
Panel1.Controls(0).Dispose()
Loop
' Create form by its full name.
Dim T As Type = Type.GetType("Namespace." & frm_Name)
Dim frm As Form = CType(Activator.CreateInstance(T), Form)
' Load form into the panel.
frm.TopLevel = False
frm.Visible = True
frm.Dock = DockStyle.Fill
Panel1.Controls.Add(frm)
' ???
myInterface = DirectCast(frm, IOnEvent)
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) _
Handles DataGridView1.SelectionChanged
' Avoid error if the panel is empty.
If myInterface Is Nothing Then Return
' Run subroutine in the loaded form.
myInterface.OnSelectionChange()
End Sub
End Class
One last thing – it would be great if someone could take a quick look at the code (it works) and confirm that it is ok, especially the lines marked with “???” (I don’t understand them yet).

Check if any dialog is open

Does anybody see my mistake here?
I am unable to recognize if a form is shown as a dialog in my app.
Public Class Form1
Private m As Form2
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Me.Text = DateTime.Now.ToLongTimeString & " " & IsAnyDialogShown()
End Sub
Public Function IsAnyDialogShown() As Boolean
For Each f As Form In Me.OwnedForms
If f.Owner Is Me Then
Return True
End If
Next
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
m = New Form2
m.ShowDialog()
End Sub
End Class
What you are looking is for the property modal.
Check if the form's modal property is true (that is meaning that the form is showed with ShowDialog)
For Each f As Form In Me.OwnedForms
If f.Modal=True Then
'your code here
End If
Next
Now for your mistake (I haven't visual studio to try it right now) but your IsAnyDialogShown(), it seems that it returns always true :
For Each f As Form In Me.OwnedForms ' (So f belongs to Me)
If f.Owner Is Me Then 'f.Owner is always me because you are seaching in forms that have as owner the Me form
Return True
End If
Next
Hope I helped a little.
Tell me if I can do something more
So after your comments.
Try this:
For Each frm as Form In Application.OpenForms
If frm.Modal=True Then
'do something
'Actually you should have only one form because only one can be in modal state
end if
Next
You need to check Visible property of the form, which is the boolean.
If it is true, then form is shown, else it's hidden.
That's just doing forms owned by Me. Nothing to do with whether they are dialog forms.
ie.e it will pick up normal forms.
Also if you want this to work as expected , you should use the overload where you pass the owner.
as in m.ShowDialog(Me);
Not something I've ever done but if Owner isn't me in Me.OwnedForms I want my money back.

VB.NET Form Hiding Issue

I have a custom form, B. B is created by A, which has a handle to B.VisibleChanged.
B only has an OK and Cancel button on it, and I want to do some logic when OK is hit.
B's OK button is dealt with like this:
Me.Result = Windows.Forms.DialogResult.OK
Me.Hide()
The code in A is properly hit and run, but it never hides B. When I check the values of the properties on B, it shows me Visible = False.
Does anyone have any suggestions as to the possible cause of this issue?
Edit
This form was shown using the Show() command, as I'm making a later call to have the form flash using FlashWindow().
Not exactly sure about your question.
why not use me.Close() instead of me.Hide?
Is it OK to have multiple instances of B at a time? If not, go for ShowDialog.
If you can rephrase the question, someone can probably resolve your problem.
I suppose you want to display a messagebox with an ok & cancel button. Instead of using a form use a mesagebox.
eg:
DialogResult dgResult = MessageBox.Show("Click Yes or No", "Test App", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (DialogResult.OK == dgResult)
{
//Do what you want.
}
else
{
//Do nothing.
}
If you are going to use a form, to do that & wanted to modify the parent's form, it would be advisable to use delegates to prevent form B from modifying form A's variables.
Else: (Not recommended)
Declare form B as a member variable of form A.
when required instantiate form B.
do B.ShowDialog();
internally in OK & cancel do this.dispose();
Again when you need form B just instantiate. re - instantiation will not be too much of an overhead if you dont call it very often.
But if you only need OK Cancel, use message box instead.
The show/hide approach works for me:
Public Class frmViewChild ' your form A
Private WithEvents _edit As frmEdit
'code
Private Sub editCell()
Dim PKVal As String
Dim PKVal2 As String
Dim fieldOrdinalPos As Integer
Dim isLastField As Boolean
If _edit Is Nothing Then
_edit = New frmEdit
_edit.MdiParent = Me.MdiParent
End If
'code
_edit.init(<params>)
If Not _edit.isNothing Then
_edit.Show()
_edit.WindowState = FormWindowState.Maximized
_edit.BringToFront()
End If
End Sub
'code
Private Sub _edit_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles _edit.VisibleChanged
If Not _edit.Visible Then
WindowState = FormWindowState.Maximized ' revert after closing edit form
End If
End Sub
Public Class frmEdit ' your form B
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim ret As Integer
doOK(ret)
If ret > -1 Then ' no error
Me.Hide() ' close form, but didn't cancel
End If
End Sub
HTH