Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have 2 forms in a program in which i want to pass the input from form 1 to form 2. I want to close form 1 after form 2 is opened so that the program stops running when all forms stop showing up on the screen; However, i won't be able to close form 1 if i want to pass the value into form 2 (If i can in classes, please let me know) so i hide it after form 2 is open. This, consequently, results in the program running forever even after form 2 is closed, form 1 staying hidden. I want to close form 1 whenever the user closes form 2 using the Close (X) button. Any idea how to implement this? Also, i have already set the program to 'When the last form closes'.
Also, i have already set the program to 'When the last form closes.
You almost there.
As I understand, you are keeping the Form1 opened but hidden to access it's members and/or objects from Form2 and that is the only reason why you are keeping Form1 opened.
You could solve this problem by creating a parameterized constructor in Form2 to pass whatever you need from Form1 before you close it.
Sub New(obj1FromForm1 As obj1Type, obj2FromForm1 As obj2Type, ....)
Me.New 'Don't forget this!
'Update Form2 accordingly...
End Sub
Where the obj1Type, obj2Type are the types of the passed objects. (Integer, String, ...etc.)
You could also declare class variables to refer to these objects if you need to access theme later somewhere in your Form2's code.
Private obj1 As obj1Type
Private obj2 As obj2Type
Sub New(obj1FromForm1 As obj1Type, obj2FromForm1 As obj2Type, ....)
Me.New
obj1 = obj1FromForm1
obj2 = obj2FromForm1
End Sub
Now back to your Form1. Make sure that you Close it once you create Form2 using its new parameterized constructor and showing it.
Private Sub Form2Caller()
Dim f As New Form2(obj1 As obj1Type, obj2 As obj2Type, ....)
f.show
Me.Close() 'and not Me.Hide nor Me.Visible = False.
End Sub
One last point. Don't pass disposable objects to Form2 that will be disposed by Form1 when you close it.
Good luck.
Related
I have Two Forms
In The First Form I Have A Textbox Called TB1 An A String Called S1
In The Second Form I Have A Label Called L1
I Declared them publicly in a module
Module M1
Public L1 As New Label
Public TB1 As new Textbox
Public S1 As new String
End Module
/../
'in the First form
S1=TextBox1.text
'in the second form
L1.text=S1
But I Get this error "System.NullReferenceException" on the first Label L1
Any ideas why i'm getting this error
Try something like this:
On Form1 in the event calling Form2, Add:
Form2.L1.Text = TextBox1.text
Form2.Show()
You can't put them in a module like that; nothing will see them.
In addition, there's no way to see how this code is flowing.
To do a simple exercise:
Draw first form - form1 with Textbox1 on it.
Make the first form startup form (it will be by default in new winforms project)
Draw 2nd form - form2 with Label1 on it.
Put a button on the first form
Double click the button
In the handler put this code:
Sub Button1_Click (etc...
dim Form2Instance as new Form2
Form2Instance.Label1.Caption = Textbox1.text
Form2Instance.ShowDialog
End Sub
You can put a textbox on form2 and read the results in form1 the same way.
You can tell if the user OK'd (not canceled) form2 like this:
if Form2Instance.ShowDialog() = DialogResults.OK then
' only do this code if they HIT OK
I suggest maybe hitting youtube or pluralsite and watching a 'winforms for beginners' video, if such a thing exists. There are a lot of traps and pitfalls that you will run into hacking away on your own, that will be explained to before hand if you learn the basics. This is especially true if you've only done web programming or are just learning programming.
I am working on a project that has WebBrowsers in Other Forms;
I wrote the code below to control these WebBrowsers; but I need the code to recognize (Declare) the WebBrowsers of these forms.
Dim openForm As Form = Nothing
For Index As Integer = My.Application.OpenForms.Count - 1 To 0 Step -1
openForm = My.Application.OpenForms.Item(Index)
If openForm IsNot Me Then
MyWebBrowser.navigate("http://www.google.com/") ' PROBLEM IN THIS LINE
End If
Next
My Module created them as below:
Module MMMBrowser
Dim frmNew As New Form
Dim MekdamBrowser As New WebBrowser
Other info gleaned from comments:
there is form factory of some sort which creates new frmNew
there are many of these open at a time, which is the reason for the backwards loop thru OpenForms to find the last one.
The MekdamBrowser reference is an attempt to refer to the browser on the form.
The easy things is to provide a way for outsiders to tell the form to navigate somewhere using a new Sub, and let the form drive the browser control. This probably eliminates the need for a global MekdamBrowser reference. In the browser form add something like this:
Public Sub GotoNewURL(url As String)
myWebBrowserName.navigate(url)
End Sub
This procedure only exists for Form1 not the generic Form type, so we need to change how you find the form to use. Your existing loop is wonky. It will only ever find the last instance of a form which is not the current form. If you add a third form type, it wont work well:
Dim lastBrowserFrm As Form1 ' use the class name!
' this will try to get the last Instance of Form1
lastBrowserFrm = Application.OpenForms.OfType(Of Form1)().LastOrDefault
' LastOrDefaultcan return nothing if there are none,
' so test
If lastBrowserFrm IsNot Nothing Then
lastBrowserFrm .GotoNewUrl("www.stackoverflow.com")
Else
' create a new one, I guess
End If
Your loop was not considering that there could be other form types in the collection which are not Form1 or even if a new browser form was the last one created! This is more important now because GotoNewURL is only available on Form1 instances.
I changed the name to lastBrowserFrm to reflect what is really going one - it will just find the last one created. If you are trying to work with a specific instance, you need to provide a way to track the ones you create such as with a List(of Form1) or use the Name property so you can tell one from the other. As is, you do not a way to get back a specific form instance.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
In VB, I create 2 forms in 1 project. In form1, I put 3 buttons with different value. In form2, I only put 1 textbox with no value.
My question is, how if I press one of the button in form1, the form2 is automatically opened and the value from the button that I press automatically added to the form2 textbox?
Add following code into your button handler. You can double click button and add the code into event handler which is automatically created:
'Here we are creating actual object and passing string into it constructor method
Dim instanceOfForm2 = new Form2("String value from Form1!")
instanceOfForm2.Show() ' Showing form
In Form2 we need to tweak our constructor to accept one parameter:
Public Sub New(someValue as String)
InitializeComponents() 'This is always first row in form constructor
TextBox1.Text = someValue 'And put that text into textbox...
End Sub
In VB6 you can do all the stuff that lardymonkey has in place, but you don't have to. The most concise way to do what you want is this. First, make your three command buttons in Form1 into a control array. To do this, give them all the same name (I'll use "cmdMyButtons" in my example), and set their index properties to 0, 1, and 2. Then do this in Form1's code window:
Option Explicit
Dim ButtonText(2) As String
Public Sub Form_Load()
ButtonText(0) = "First Button Text"
ButtonText(1) = "Second Button Text"
ButtonText(2) = "Third Button Text"
End Sub
Public Sub cmdMyButtons_Click(Index As Integer)
With Form2
.txtMyTextBox.Text = ButtonText(Index)
.Show vbModal
End With
End Sub
Now, I like lardymonkey's idea of showing modally, so I put it in here as well. However, several things in his code sample aren't intrinsically necessary to do what you want, and create overhead, so I pulled them out:
You don't need to make a property; you can just set the text
directly as I have here.
You don't need to create a form variable; you can just reference the form directly as I have here.
You don't have to load the form explicitly; the form gets
automatically loaded as soon as you set the variable (by the way,
the Show method also automatically loads the form, too--you only use
Load when you want to have the form loaded into memory before you do
anything to it).
If you close the modal form it will be
automatically unloaded. However, unloading a form doesn't set any
object variables referencing it to nothing. Therefore, frmDetail
will not be Nothing when you check it, you will unload a form that
isn't loaded. While this doesn't throw an error (the statement is ignored), I wouldn't do it anyway. So, you don't
need any of the "make sure the form is destroyed" code.
And now, for a short lecture on the whole business of always explicitly destroying object variables:
There is a longstanding argument about whether you need to explicitly set all your local object variables to Nothing before exiting a subroutine in VB6. I don't agree with this at all; VB takes care of this automatically when the variables go out of scope. As far as I can see, the reason that people believe that they have to do this is that the scope finalizer doesn't collect garbage in any particular order, and sometimes two interacting COM objects need to be destroyed in a particular order due to poor coupling architecture. In such a case, you do indeed need to clear the objects in the correct order to work around intermittent bugs, so the myth developed that VB's garbage collection is buggy and needs to be circumvented by always manually destroying object variables.
Frankly, the idea that a programmer is going to always do this and never forget is naive. So I persist in disagreeing with it; the developers of VB6 put a lot more thought and effort into developing the scope finalizer than any programmer is going to put into circumventing it.
Without knowing the specific version of the software you are using we cant answer, we can answer it if you provide the correct version
In .net it's a simple as creating the form then passing the value over.
Friend objForm2 as New Form2
Private Sub button1_Click(ByVal sender As System.Object, ByVal e as System.EventArgs) Handles button1.Click
objForm2 = new Form2()
TextBox1.Text = value
End Sub
This would be a way of doing it in VB6. I've left the error handling up to you.
I've made the assumption that the name of the text box is txtOutput on form2.
In Form2 add the following:
Option Explicit
Public Property Let OutputText(ByVal strOut As String)
txtOutput.Text = strOut
End Property
In Form1 add the following:
Option Explicit
Private Sub Command1_Click()
DisplayForm "1"
End Sub
Private Sub Command2_Click()
DisplayForm "2"
End Sub
Private Sub Command3_Click()
DisplayForm "3"
End Sub
Private Sub DisplayForm(ByVal strValue As String)
'Declare the variables
Dim frmDetail As Form2
'Create the form
Set frmDetail = New Form2
'Load the form and display it modal
Load frmDetail
frmDetail.OutputText = strValue
frmDetail.Show vbModal, Me
'Make sure the form is destoryed
If Not frmDetail Is Nothing Then
Unload frmDetail
Set frmDetail = Nothing
End If
End Sub
Make sure you comment the code and if you need some error handling then add it. If you need help with the VB6 functions you can find it here MSDN VB6 Reference
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Some basic terms that interchange that i have no one to ask, and i guess to stupid to understand my self.
Method,procedure, parameters, operation, operator, function, instaniantiantion, separator,
I really need help!
I really need to see a long module of code that every thing is broken down for a stupid guy like me.
For instance break this down, not what it does but how it does it, and the terminology. Word by word,, all dots, = parentheses, the passes the gets all that stuff, I know that this is simple to everyone else. And i will need more help until i get it... Maybe we can work something out. Some one that is available,,, that knows this stuff backwards and forwards and has the patience, that would like to help me... I have tried books i just do not get it HELP
Public Class ViewerForm1
Private Sub btnSelectPicture_Click(sender As Object, e As EventArgs) Handles btnSelectPicture.Click
'Show the open dialog box.
If ofdSelectPicture.ShowDialog = DialogResult.OK Then
'Load the picture in the box.
btnSelectPicturePicture.Image = Image.FromFile(ofdSelectPicture.FileName)
'Show the name of the file in the forms caption.
Me.Text = "Picture Viewer "(ofdSelectPicture.FileName)
'Close the window at exit the application.
Me.Close()
End If
End Sub
Private Sub btnSelectPicture_Click(sender As Object,
e As EventArgs) Handles btnSelectPicture.Click
This line declares a default Click event handler and binds button's click event to it.
If ofdSelectPicture.ShowDialog = DialogResult.OK Then
Opens an open file dialog and if user presses OK, processes the result.
btnSelectPicturePicture.Image = Image.FromFile(ofdSelectPicture.FileName)
Loads the image into the button, based on the file previously selected.
Me.Text = "Picture Viewer "(ofdSelectPicture.FileName)
Line does not make sense and probably won't compile. Missing a & or a + for string concatenation. Assuming it had one, it would assign a form caption/title to a constant value + a file name that was selected.
Me.Close()
Closes the current form.
I need to share variables across two forms in VB.NET. One of them is the main form and the other is a child form.
I have been searching, and I have found a few methods. I want to use the best method to do this. I have listed a few options below. Please comment on which one would be the best option:
Create a static/shared variable in one of the forms and access it in the other forms via:
Form1 frm = new Form1(); // Creating object of parent to access shared variable
frm.a = "abc"; // Passing value
Send an instance of the main form to the child form when creating the child form. The variables can then be accessed via a property function.
Create global variables in a module. This seems like the easiest option, but I doubt it is the best option.
I also read something about delegates and events, but I don't know how to implement this.
If there is another method I haven't mentioned, please share it with me.
There is no one answer to the question. All the methods you listed should 'work.' Which you should use depends why you want to share the variable. For example:
Say you have a form with a list of records, and the user double-clicks a record, so you want to open a new form to edit the record, and you want to pass the record ID. In this case I would add a constructor method to the second form:
Sub New(RecordID as String)
'Add code to load the record here
End Sub
Say some of the forms in your application may want to know the database path or something else global like that. For that, I would make the appropriate variable on the parent form into a Public variable (called a Field) and access it as MainForm.FieldName. (Disclaimer: Purists will say you shouldn't rely on the somewhat messy fact that VB.NET automatically instantiates an instance of the form class and lets you refer to it by the form name, and that you should instead get a pointer to the actual instance of the form and store it in your child form and access the parent form like that. Actually, this is like number '2' in your post. But it's not actually necessary if you don't mind programmatical incorrectness.)
Say there is something global in your app, like the time the app was started, so you can tell the user "You've been using the app for 5 hours, go get a life!" These things could be stored in a module. (Or in the application class but that's quite hidden)
Create two forms. Add 3 radio buttons and 1 button to form1. Add a label to form2. In the code for form1 type
Public rdb As Integer = 1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.Show()
If RadioButton1.Checked Then
rdb = 1
ElseIf RadioButton2.Checked Then
rdb = 2
ElseIf RadioButton3.Checked Then
rdb = 3
End If
End Sub
Then in form2's code
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = Form1.rdb
End Sub
Store your global variables in a Module1.vb file, they must be publicly declared to be accessible from all forms:
Public X as String
Public Y as Integer
Then just use them as you would any other variable on any page:
X = "Hello"
Y = 10
Textbox1.Text = X
Textbox2.Text = Y
It's not the safest practice so it shouldn't be used for all your variables. But it is very neat and simple.
The child form can have public get and set functions for a private variable, and the parent form can set it when it changes and its end, or get it before it uses it to see if it has changed in the child form.
You can add public properties to either form. They can access those properties from each other. (That is not called shared though, and is not static in most cases.)
Not sure if this answers the question but one thing I found useful was to refer to the variables in form1 while programming in form2 as Form1.variablename and when in Form1 and referring to variables in Form2 to use in Form1 as Form2.variablename Basically, refer to variables in other forms by putting the name of the form they are in followed by a . and then the variable name