0

Apologies if this is newbie question as i'm a newbie on .net myself. So here it goes, I have 2 Forms. Form 1 and Form 2. I'm currently in form 1 and I want to pass a value to a variable on form 2. Here's the declaration on forms.

Public Sub Form1
    Dim TempForm as Form = Form2   
End Sub

Public Sub Form2
    Dim Id as Integer
End Sub

So I have the Form2 that can be accessed using TempForm and I know there is a variable named Id in Form 2 and I want to pass a value to it before opening. Please note that I cannot pass the value to the Form 2 directly and it should be to Temp form as I intend to make it dymamic so I can also use it to open other forms. Thanks a lot!

2
  • Sounds like you should implement a constructor. Commented Sep 7, 2017 at 4:44
  • i'll do what you're asking.. hold on Commented Sep 7, 2017 at 4:46

1 Answer 1

2

Use this code:

Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim NewForm As New Form 'make a new form
    'assign the value 50 to the variable ID
    Dim IDx As New NewForm(50)
End Sub
End Class

'for new form 
Public Class NewForm
    Public ID As Integer
    'Here's the class constructor
    Public Sub New(Value As Integer)
        ID = Value
        'use this ID however you want
    End Sub
End Class
Sign up to request clarification or add additional context in comments.

3 Comments

In case you saw my previous comment I misread your code, but this line is not necessary: Dim NewForm As New Form - otherwise it's fine :)
Thanks a lot it worked with some minor twix. Just gonna add that it needs to InitializeComponents first. Also just a follow up, in case I only know the form by string, how can I cast it as a form. Example I have a string OpenForm = "Form2". How can use it in the above code to make it more dynamic? Thanks a lot
@VisualVincent I was looking all over for this but not hard enough i suppose. Now i just need to combine this two codes. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.