I am working in c# windows application.I have two windows from name as form1 and form2.i am calling form2 by clicking the button in form1 but i create the object for form2 in constrcutor of form1 .if i click the button first time form2 showed successfully after that i close the form2 by clicking the default close button and again click the button now i am getting object disposed exception was unhandled exception.how can avoid this?
Don't handle the exception, fix the bug in your code. The form instance is dead after the form is closed, you cannot show it again. Either write it like this:
private void button1_Click(object sender, EventArgs e) {
var frm = new Form2();
frm.Show(this);
}
Or if you want only one instance of the form to be ever visible:
Form2 theForm;
private void button1_Click(object sender, EventArgs e) {
if (theForm != null) {
theForm.WindowState = FormWindowState.Normal;
theForm.BringToFront();
}
else {
theForm = new Form2();
theForm.FormClosed += delegate { theForm = null; };
theForm.Show(this);
}
}
You are keeping a reference to the object (window here) but you are closing it. Object is disposed but is not garbage collected. Your reference here is invalid now as the object has lost its usable state.
You need to hide the form instead of close if you need to re-use it. Or create a new instance to load it again.
You can use events in order to let form1 know when form2 has been closed and clear its reference to it. Then form1 doesn't need to call form2 if it has been closed.
We do something similar here with a few of our tools that plug into third-party apps. Code sample below:
public class Form1 : Form
{
private Form2 otherForm;
private void ActivateForm2_Click(object sender, EventArgs e)
{
if (otherForm == null || otherForm.IsDisposed)
{
otherForm = new Form2();
otherForm.FormClosed += new FormClosedEventHandler(otherForm_closed);
}
otherForm.Show(this);
}
private void otherForm_Closed(object sender, FormClosedEventArgs e)
{
otherForm.Dispose();
otherForm = null;
}
}
Related
So I want to show a form and close the other form so I did this in form1:
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 x = new Form2();
x.Show();
this.Hide();
//didn't use this.close() cause then the whole program will close instead of
//just the current form
}
Then I wanted the main form to open again after the 2nd form is closed so I did this in form2:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 x = new Form1();
x.Show();
}
Now the problem is when I'm back in the main form after closing the 2nd form. if I close the main form it doesn't fully close and still remains open in the background (I found it in task manager). I think its because the "show" method just opens another form instead of making the form appear so the main form which got hidden is still there running in the background.
what should I do to make the form get closed when I exit it?
I tried putting this.close(); in the form closed and form closing event but both resulted in a crash.
When you write:
Form1 x = new Form1();
you are creating a new Form1 object, so x refers to the new one and not to the original one. Instead, you could use this:
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var form2 = new Form2())
{
this.Hide();
form2.ShowDialog();
}
this.Show();
}
When ShowDialog() is called, the code following it is not executed until after the dialog box is closed, so this.Show() will execute only after Form2 is closed.
Another option is to simply subscribe to the FormClosed() event of Form2 when you create it, then un-hide your instance of Form1 from there:
// ... all in Form1 ...
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
Form2 x = new Form2();
x.FormClosed += X_FormClosed;
x.Show();
}
private void X_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
So then when you close Form2 your instance of Form1 will automatically re-appear.
In a c# I have two forms: Windows Form1 & Windows Form2.
When I click on a link label in Form1, the second form is shown. But when I close the second form, my first Windows form closes too.
my main form is:
namespace Windows_Forms_Basics
{
public partial class ShowLocationOnMapForm : Form
{
private string latitude;
private string longitute;
private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
public ShowLocationOnMapForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watcher = new GeoCoordinateWatcher();
// Catch the StatusChanged event.
watcher.StatusChanged += Watcher_StatusChanged;
// Start the watcher.
watcher.Start();
}
private void button_ShowOnMap_Click(object sender, EventArgs e)
{
textBox_Latitude.Text = latitude;
textBox_Longtitude.Text = longitute;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]
private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) // Find GeoLocation of Device
{
try
{
if (e.Status == GeoPositionStatus.Ready)
{
// Display the latitude and longitude.
if (watcher.Position.Location.IsUnknown)
{
latitude = "0";
longitute = "0";
}
else
{
latitude = watcher.Position.Location.Latitude.ToString();
longitute = watcher.Position.Location.Longitude.ToString();
}
}
else
{
latitude = "0";
longitute = "0";
}
}
catch (Exception)
{
latitude = "0";
longitute = "0";
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
}
}
and my second form is:
namespace Windows_Forms_Basics
{
public partial class HelpForm : Form
{
public HelpForm()
{
InitializeComponent();
}
private void HelpForm_Load(object sender, EventArgs e)
{
}
private void button_BackToForm1_Click(object sender, EventArgs e)
{
ShowLocationOnMapForm form1 = new ShowLocationOnMapForm();
this.Hide();
form1.Show();
}
}
}
Do you have any idea how to tackle this problem?
I am guessing you may be “confusing” forms and one forms “ability” to access another form. Let’s start by taking a look at the bit of code in your initial question…
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.Hide();
form2.Show();
}
This code is called from (what appears to be) a Form named ShowLocationOnMapForm.
On this form is a LinkLabel named linkLabel_help and its LinkClicked event is wired up and is shown above.
In addition, there appears to be a “global” variable form2 that is a HelpForm object (first line in the code above), which is another form. It is unnecessary to create this “global” form variable in the ShowLocationOnMapForm. …. However, we will continue as it is not pertinent at this point.
When the user “clicks” the `LinkLabel’ the above method will fire.
On the first Line in the method…
this.Hide();
Is going to “hide” the current form ShowLocationOnMapForm … and “show” the second form (HelpForm) with the line…
form2.Show();
On the surface, this may appear correct, however, there is one problem that I am guessing you are missing. The problem is…
How are you going to “unhide” the first form ShowLocationOnMapForm?
The second form (HelpForm) is “shown”, however, it isn’t going to KNOW anything about the first form. In this situation the first form is basically LOST and you have no way of accessing it. Therefore when you attempt the line… form1.Show(); in the second form, the compiler is going to complain because its not going to know what form1 is. In this code, there is NO way to get back to the first form. It is not only hidden from the user, but from the second form’s perspective the “CODE” can’t see it either!
Your faulty solution is not only “creating” another form1 but it is also doing the same with the second form.
Given this, it appears clear, that if you want to keep access to the first form… then you are going to have to use a ShowDialog instead of Show OR pass the first form to the second form.
Since it is unclear “how” you want these forms to interact, I can only proffer two (2) ways that you can use to at least keep access to the first form.
1) Use ShowDialog instead of Show when displaying the second form. It may look like …
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
HelpForm form2 = new HelpForm();
this.Hide();
form2.ShowDialog();
this.Show();
}
In the code above, the ShowDialog is going to “STOP” code execution in the first form and will wait for the second form (form2) to close. When executed, the first form is hidden, then the second form is shown, however, unlike the Show command, the line this.Show(); will not be executed until the second form closes. I am guessing this may be what you are looking for.
2) Pass the first form to the second form giving the second form “access” to the first form.
This will require that the second form has a “constructor” that takes a ShowLocationOnMapForm object as a parameter. With this, the second form can create a “global” variable of type ShowLocationOnMapForm that “points” to the first form. The constructor may look like…
private ShowLocationOnMapForm parentForm;
public HelpForm(ShowLocationOnMapForm parent) {
InitializeComponent();
parentForm = parent;
}
In the first form, you would instantiate the second form with...
HelpForm form2 = new HelpForm(this);
With this approach, the second form will have total access to the first form. You could add the “back” button as you describe and simply execute the line…ParentForm.Show(); However, I recommend you also wire up the second forms FormClose event and show the first form, otherwise, if the user clicks the close button (top right) and doesn’t click the “back” button, then you will have LOST the first form again.
Without knowing “exactly” how you want these forms to interact it is difficult to proffer a complete solution.
There are also other ways to accomplish this, however these should work for most cases.
I hope this makes sense and helps.
I tried to solve this problem by placing a 'Back to Form1' button in Form2. Which works, and the solution is as follows:
on my Form1 I have:
private Form2 form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
and on my second form I have:
private void button_BackToForm1_Click(object sender, EventArgs e)
{
HelpForm form1 = new HelpForm();
this.Hide();
form1.Show();
}
But the problem is if I click the close button (on top right of the window) instead of the GoBack button on the second form, Form1 & Form2 both close in the same time.
I have a program which opens two forms
and I want when I click on Form1
then Focus on Form2.
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Focus();
}
But this doesn't work, what's wrong in my code?
EDIT:
I found already answered Here by #moguzalp at the comments
First of all that Form2 is never visible.
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
frm2.Focus();
}
If that Form is visible though with your code, that means you need to get same reference and call Focus() against it.
EDIT:
Then you need to have a reference to that Form.
At some point you created that Form and assigned it to a vairable/field or anything like that.
You need to call Focus or Activate against it.
Example:
Inside Form1 when you create a Form2 instance:
public class Form1 : Form
{
private Form _frm2;
//That code you probably have somewhere. You need to make sure that this Form instance is accessible inside the handler to use it.
public void Stuff() {
_frm2 = new Form2();
_frm2.Show();
}
private void Form1_Click(object sender, EventArgs e)
{
_frm2.Focus(); //or _frm2.Activate();
}
}
If you can have a form opened, try finding it:
using System.Linq;
...
// Do we have any Form2 instances opened?
Form2 frm2 = Application
.OpenForms
.OfType<Form2>()
.LastOrDefault(); // <- If we have many Form2 instances, let's take the last one
// ...No. We have to create and show Form2 instance
if (null == frm2) {
frm2 = new Form2();
frm2.Show();
}
else { // ...Yes. We have to activate it (i.e. bring to front, restore if minimized, focus)
frm2.Activate();
}
If you want to Show your frm2, you should call frm2.Show(); or frm2.ShowDialog();.
Also, before 'Show' call you can set frm2.TopMost = true; if you want this form to be on the top.
So it could be:
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.TopMost = true;
frm2.Show();
}
If you already opened the form elsewhere, then this code will not work as it's a new instance of Form2 and not the one that is opened.
You will have to keep a reference to the form that is opened, and then use Focus or might be better Activate on it.
if the form is opened from within Form1 then:
Add a field for holding current reference of Form2
Save it when showing the form.
Use it when focusing
private Form2 currentForm2;
....
this.currentForm2 = new Form2();
this.currentForm2.Show();
...
...
this.currentForm2.Activate();
I am working in compact framework 3.5,i am working on windows mobile application.
form1.cs
internal void menuItem_Click(object sender, EventArgs e)
{
this.Close();
form2 obj = new form2();
obj.ShowDialog();
/////other code
}
form2.cs
public void backbutton_Click(object sender, EventArgs e)
{
form1 obj = new form1();
obj.ShowDialog();
/////other code
}
Initially i am in form1 and i am navigating to form2.In form2,a back button is there and on clicking backbutton i need to show the from1.Now i can show the form1 on backbutton click,but i need to close the previous opened form1.
I tried with this.Close() and this.Dispose(). This makes me exist from my application.
How to do this in compact framework.
Best way to work with that kind of things is using a singleton. When you show your first form, you instance the first form, then you show the second creating it instance and hiding the first one (use hide(), not close(), then your instance will still on memory). On back button click, you only have to hide() the second, and show() the first.
I would recommend instead of creating new form1 from form2, just close form2 and go back to form1:
form2.cs:
public void backbutton_Click(object sender, EventArgs e)
{
this.Close();
}
form1.cs:
internal void menuItem_Click(object sender, EventArgs e)
{
form2 obj = new form2();
obj.ShowDialog();
/////other code
}
I have form which is opened using ShowDialog Method. In this form i have a Button called More.
If we click on More it should open another form and it should close the current form.
on More Button's Click event Handler i have written the following code
MoreActions objUI = new MoreActions ();
objUI.ShowDialog();
this.Close();
But what is happening is, it's not closing the first form. So, i modified this code to
MoreActions objUI = new MoreActions ();
objUI.Show();
this.Close();
Here, The second form is getting displayed and within seconds both the forms getting closed.
Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.
Any kind of help will be really helpful to me.
In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:
// MainForm
private ChildForm childForm;
private MoreForm moreForm;
ButtonThatOpenTheFirstChildForm_Click()
{
childForm = CreateTheChildForm();
childForm.MoreClick += More_Click;
childForm.Show();
}
More_Click()
{
childForm.Close();
moreForm = new MoreForm();
moreForm.Show();
}
You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.
If I got you right, are you trying like this?
into this?
in your Form1, add this event in your button:
// button event in your Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2
}
then, in your Form2 add also this event in your button:
// button event in your Form2
private void button1_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3(); // Instantiate a Form3 object.
f3.Show(); // Show Form3 and
this.Close(); // closes the Form2 instance.
}
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.
For the Ex
Create three windows froms
Form1 Form2 Form3
Add One button to Form1
Add Two buttons to form2
Form 1 Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
if (f2.ShowMoreActions)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
Form2 code
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public bool ShowMoreActions = false;
private void button1_Click(object sender, EventArgs e)
{
ShowMoreActions = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
Leave form3 as is
Try this..
//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
this.Visible = false; // this = is the current form
SignUp s = new SignUp(); //SignUp is the name of my other form
s.Visible = true;
}
private void Button1_Click(object sender, EventArgs e)
{
NewForm newForm = new NewForm(); //Create the New Form Object
this.Hide(); //Hide the Old Form
newForm.ShowDialog(); //Show the New Form
this.Close(); //Close the Old Form
}
you may consider this example
//Form1 Window
//EventHandler
Form1 frm2 = new Form1();
{
frm2.Show(this); //this will show Form2
frm1.Hide(); //this Form will hide
}
For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.
your name example=form2.
form2 obj=new form2();
obj.show();
To close form1, write the following code:
form1.visible=false;
or
form1.Hide();
You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.
It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.
You need to control the opening of sub forms from a main form.
In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.
In Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Validation flag
public static bool ValidLogin = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
if (ValidLogin)
{
Application.Run(new Form1());
}
}
}
In Login.cs:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "x" && txtPassword.Text == "x")
{
Program.ValidLogin = true;
this.Close();
}
else
{
MessageBox.Show("Username or Password are incorrect.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Use this.Hide() instead of this.Close()
Do this to Program.cs
using System;
namespace ProjectName
{
public class Program
{
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetDefaultCompatibleTextRendering(false);
new Form1().Show();
Application.Run();
}
}
}