I am currently just practicing code on Visual basic. Basically, I created a windows form with many texts on it. each text is the name of a color txtRed, txtBlue, etc.
I am trying to create a simple action where i would right-click on the red text (on my windows form) and a submenu should open. Then when i click on open in the submenu, a new windows form should open and show a text "this is red".
That is the result im trying to achieve at least. Any advice on how to accomplish this? I am lost. Any help would be much appreciated. Thank you in advance.
Sorry, I am also a new contributor like Aminul, and do not have the rep to add a comment yet, so have added this comment as an answer.
Aminul's answer is close to correct, but in addition to jmcilhinney's comment, as I have seen so many times, the instantiation of the new form is incorrect in his example. Always make sure that any objects that are disposable actually get disposed when they are no longer needed. In this instance, I would create the variable for the form at a higher level and tie into its Closed event. Also, the Form2 class he coded is not correct as it does not inhert the form control so would not have access to the base Form class events.
Below is an example of a dynamically generated form as was partially introduced in the previous example; however, it would be easier to just create a new form in the designer and add the necessary controls. The closed event can still be tied into, but would require a lot less code:
Public Class Form1
Private redForm As Form2 = Nothing
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
If redForm Is Nothing Then
redForm = New Form2
AddHandler redForm.Closed, AddressOf redForm_Closed
End If
redForm.Show()
End Sub
Private Sub redForm_Closed(sender As Object, e As FormClosedEventArgs)
redForm.Dispose()
redForm = Nothing
End Sub
Public Class Form2
Inherits Form
Private lbl As Label = Nothing
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Red Form"
lbl = New Label
lbl.Text = "This is red"
lbl.AutoSize = True
lbl.Location = New Point(10, 10)
Me.Controls.Add(lbl)
End Sub
Private Sub Form2_Disposed() Handles MyBase.Disposed
lbl.Dispose()
lbl = Nothing
End Sub
End Class
End Class
Below is an example using a separate form created in the studio designer assuming that the name of the other form is Form2 and already has it's contained controls defined within the designer:
Public Class Form1
Private WithEvents redForm As Form2 = Nothing
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
If redForm Is Nothing Then
redForm = New Form2
End If
redForm.Show()
End Sub
Private Sub redForm_Closed(sender As Object, e As FormClosedEventArgs) Handles redForm.Closed
redForm.Dispose()
redForm = Nothing
End Sub
End Class