C# Close windows form - c#

I am opening up another form when a button is clicked, but can't decide how to close the current form when doing this. This is the code:
private void nextSportButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < Form1.sportsAdded; i++)
{
if (Form1.sportOpened == i)
{
Form1.IDNumber = Form1.sportIDArray[i];
OutputForm OutputForm = new OutputForm();
OutputForm.ShowDialog();
}
this.Close();
}
}

Calling OutputForm.ShowDialog() waits until OutputForm is closed and only then returns to execute further code. You want to use OutputForm.Show() instead.
Note: If "this" is the main form (the first form shown) of your application, closing "this" will terminate the whole application.

Use this.Hide(); instead of this.Close(); and using this.Close(); inside a for loop should throw an exception.

first hide current form don't close after open your new form,
this.Hide();
Form1.IDNumber = Form1.sportIDArray[i];
OutputForm OutputForm = new OutputForm();
OutputForm.ShowDialog();

Related

Error when calling Form.Show() a second time

I have a main form with a button.
OnClick of that button does the following...
Form AllBook = new Form();
//Does some other processing and SQLReader querying.
AllBook.Show();
Afterwards I close the form. When I try to show it again I receive this error.
System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'Form'.'
// objects
Form AllBook = new Form();
ComboBox booksList = new ComboBox();
ComboBox chapters = new ComboBox();
Panel topPannel = new Panel();
Panel txtPannel = new Panel();
TextBox mainText = new TextBox();
private void button1_Click(object sender, EventArgs e)
{
// add objects to form
AllBook.Controls.Add(topPannel);
topPannel.Controls.Add(booksList);
// get combobox items from another Method
int chapterCount = countChapters(43);
for (int i = 1; i <= chapterCount; i++) {
chapters.Items.Add(i);
}
topPannel.Controls.Add(chapters);
AllBook.Controls.Add(txtPannel);
txtPannel.Controls.Add(mainText);
AllBook.Show();
}
// count books chapters
public int countChapters(int bookNum) {
int chapter = 0;
switch (bookNum) {
case 1:
chapter = 50;
break;
case 2:
chapter = 40;
break;
case 3:
chapter = 27;
break;
case 4:
chapter = 36;
break;
.....
}
#H.G. Sandhagen and #LarsTech are correct.
Closing should dispose of the form. If you want to show it again you need to...
Form AllBook = new Form();
AllBook.Show();
...every time.
Edit: Adding further clarification.
Closing the form in a way calls Disopose() as well.
Source:
When a form is closed, all resources created within the object are
closed and the form is disposed. You can prevent the closing of a form
at run time by handling the Closing event and setting the Cancel
property of the CancelEventArgs passed as a parameter to your event
handler. If the form you are closing is the startup form of your
application, your application ends.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.close?view=netframework-4.7.2
By default, closing a form will dispose it. But you can change this behavior by overriding the Closing event.
So you should either:
Create a new instance of your form each time you show it, and allow WinForms to dispose it when the user closes it; or
Override the Closing event, so that closing causes the form to get hidden instead of disposed, at which point you'll be able to show the same form multiple times:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
e.Cancel = true;
}
Note that if you choose the second option, it will be up to you to call Dispose() on the form when you're done with it.
When the form is closing it automatically gets disposed, So you can refresh it before showing it again by using:
Allbook.Refresh();

How to close Login form which is coded into Form1 then show another form?

I have a Loginform which i coded into the mainform or Form1, then if all the inputed credentials are correct I will be directed to Form2 and then the Loginform will close, and the Form2 contains a logout button, and if I click the logout button I will go back to Loginform and input again the credentials.
I want to close or not to be shown in the taskbar icon the Loginform when I'm successfully login, I only want to see one icon not two icon in the taskbar.
Note:
Loginform is in the Form1, and Form2 is another form.
void btnLogin_Click(object sender, EventArgs e)
{
bool error = true;
if ((txtUserLog.Text.Trim() == "") || (txtPassLog.Text.Trim() == ""))
{
MessageBox.Show("Please fill all fields!");
}
cfgotcall.tether(settings);
cfgotcall.engageQuery("SELECT * FROM tblUsers");
unitbl = cfgotcall.tbl;
cfgotcall.untether();
for (int i = 0; i < unitbl.Rows.Count; i++)
{
if ((unitbl.Rows[i].ItemArray.ElementAt(2).ToString().Equals(txtUserLog.Text, StringComparison.OrdinalIgnoreCase)) && (unitbl.Rows[i].ItemArray.ElementAt(3).Equals(txtPassLog.Text)))
{
if (unitbl.Rows[i].ItemArray.ElementAt(4).ToString().Equals("Registrar", StringComparison.OrdinalIgnoreCase))
{
error = false;
i = unitbl.Rows.Count;
cfgotcall.engageQuery("SELECT * FROM tblUsers");
frmInterface sfInterface = new frmInterface();
sfInterface.enable_mnuSIM(true);
sfInterface.ShowDialog();
}
else if (unitbl.Rows[i].ItemArray.ElementAt(4).ToString().Equals("Accounting", StringComparison.OrdinalIgnoreCase))
{
error = false;
i = unitbl.Rows.Count;
cfgotcall.engageQuery("SELECT * FROM tblUsers");
frmInterface sfInterface = new frmInterface();
sfInterface.enable_mnuSAM(true);
sfInterface.ShowDialog();
}
}
Additional to the correct answer of #Slashy:
"Use Form1.Visible = False;" or "This.Visible = False;" because .Close() on the Mainform exists the whole program.
#Edit: ".Hide()" as #Slashy edited is also a possibility :)
You shouldn't continue after the showing the MessageBox as it wouldn't make any sense, so do something like:
if ((txtUserLog.Text.Trim() == "") || (txtPassLog.Text.Trim() == ""))
{
MessageBox.Show("Please fill all fields!");
return; // Abort continuing when no data entered
}
You can simply create a new instance of the second form and show it, simultaneously hiding the current form somthing like this:
//when login successed
Form2 form2=new Form2();
form2.Show();
this.Hide()//closes the current form.
Goodluck.
I think your approach just create more problems for your application when you need to handle login and main forms simultaneously.
On my opinion LoginForm must handle only login processing
and Main form will be shown only if LoginForm succesfully passed.
Main form and login form are different forms
Write your own Main method which will look like this:
public void Main()
{
using LoginForm login = new LoginForm()
{
if(login.ShowDialog() != DialogResult.Ok)
{
return;
}
}
//Show main form if login was succesfull
using Form1 main = new Form1()
{
main.ShowDialog();
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
ok guys thanks for your suggestion, i think i found the answer here it is and it's working on my code, a big thanks for those who help :)
this is the link:
it came from #Bhaggya Solangaarachchi
https://stackoverflow.com/a/31912692/5448305

Show or Show Dialog block other forms C#

I have 2 forms. First is a simple notepad, and i make a find function. Is works very good, but i add this.Close(); to get the resultate. If i don't close the FindForm, the action of Find button not work. I see the first form is blocked and i can't write another text. if i delete this.close() and i close FindForm after i press Find is work.
How i can open the FindForm in a new thread? i use FindForm f = new FindForm(); and f.showDialog();
If i make a Thread Th; and i use this thread to open the FindForm, my function will not work anymore. Is any method to open other form without block first form?
FindForm
public FindDialog()
{
InitializeComponent();
}
private void button_Find_Click_1(object sender, EventArgs e)
{
Form1.FindText = textBox_Text.Text;
this.Close();
}
MainForm
public void findNewToolStripMenuItem_Click(object sender, EventArgs e)
{
FindDialog gtl = new FindDialog();
gtl.Show();
richTextBox1.Select();
if (FindText != null)
{
k = richTextBox1.Find(FindText);
}
}
Calling ShowDialog will block the caller until the dialog is closed (i.e. it is modal) - if you don't want this behaviour then call Show which will open the child form modelessly (i.e. the calling code can continue)
For example, you could do something like:
public void findNewToolStripMenuItem_Click(object sender, EventArgs e)
{
FindDialog gtl = new FindDialog();
gtl.Show(); // Execution will continue immediately
richTextBox1.Select();
if (FindText != null)
{
k = richTextBox1.Find(FindText);
}
}

How to close Opened Form and open new Form on button click

I have two Winforms open at present.Out of the two one is Login form.Now as per my requirement ,if the user entered right credentials then these two opened forms needs to be closed and new form should be opened.
Means I have to close opened winforms and open new Winform on button click event of Login form.
Here i am not knowing exactly which windows are open because login form window is coming from menu button click event which is present on every form
Please help me.Thanks in advance..
Try this:
foreach (Form f in Application.OpenForms)
{
f.Close();
}
OR using for loop:
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
Application.OpenForms[i].Close();
}
OR create a list of forms:
List<Form> openForms = new List<Form>();
foreach (Form f in Application.OpenForms)
openForms.Add(f);
foreach (Form f in openForms)
{
f.Close();
}
As per you requirement, close all other forms except login form and then show that form.
foreach (Form f in Application.OpenForms)
{
if(f.Name!="frmLogin") //Closing all other
f.Close(); //forms
}
Now activate the login form.
frmLogin.Show();
frmLogin.Focus();
Application.OpenForms gets a collection of open forms owned by the application. Read more about Application.OpenForms.
You can iterate over the Application.OpenForms collection and close that you need.
you can't use foreach to close the forms as suggested in earlier replies. This is because foreach cannot be used to alter the enumerated forms list (when you Close() them, you will get a run-time error). Even if you use a for loop, you'll have to check that the main form is also not closed by mistake...
for(int i=0; i< Application.OpenForms.Count; i++)
{
Form f = Application.OpenForms[i];
if(f != this)
f.Close();
}
Instead, you can try out the below logic.
Where are these two forms getting loaded from? is it from a main form? I am assuming that both are being displayed using Form.Show() method.
In the login form login button handler, I'd accept a reference to the main form. when validation succeeds, I'd call a function LoginSuccessful() in the parent form, which would iterate through the open forms and close them.
public partial class FormMain : Form
{
LoginForm loginForm;
OtherForm otherForm;
public FormMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loginForm = new LoginForm(this);
otherForm = new OtherForm();
loginForm.Show();
otherForm.Show();
}
public void LoginSuccessful()
{
loginForm.Close();
otherForm.Close();
OtherForm thirdForm = new OtherForm();
thirdForm.Show();
}
}
LoginForm code as below:
public partial class LoginForm : Form
{
FormMain parent;
bool bLoginSuccessful = false;
public LoginForm(FormMain parent)
{
InitializeComponent();
this.parent = parent;
}
private void button1_Click(object sender, EventArgs e)
{
bLoginSuccessful = true;
Thread.Sleep(5000);
if (bLoginSuccessful == true)
parent.LoginSuccessful();
}
}
This should help you in solving your problem... Granted, it isn't the best way... It all depends upon your approach. If you are more detailed in your requirement, I can probably think out a better way.
In your login form, make default constructor private and add a new constructor and a private member like this:
private Form _callerform;
private LoginForm()
{
InitializeComponent();
}
public LoginForm(Form caller)
{
InitializeComponent();
}
Now, in the click event of button on LoginForm, try something like this:
Form SomeOtherForm = new Form();
SomeOtherForm.Show();
// Hide login and caller form
Hide();
_callerForm.Hide();
Now, you have hidden a couple of forms and opened a new one. When the user closes the application, you need to close other forms too. So,
void Application_ApplicationExit(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
form.Close();
}
}

How to close form

Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he wants to perform the action. The dialog has 2 buttons, a "Yes"-button and a "No"-button. If the user clicks the "Yes"-button, I want both DialogSettingsCancel and WindowSettings to be closed.
My button_Click event handler in DialogSettingsCancel:
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
WindowSettings settings = new WindowSettings();
this.Close();
settings.Close();
}
When I run my application, and go to the settings form, and click the "Cancel"-button, and then click the "Yes"-button, only DialogSettingsCancel closes without closing WindowSettings.
Why won't it work?
I've also tried changing
this.Close();
settings.Close();
to
settings.Close();
this.Close();
But still the same result.
You need the actual instance of the WindowSettings that's open, not a new one.
Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.
Something like this:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
You can also close the application:
Application.Exit();
It will end the processes.
new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
Why not use the DialogResult method to close the form?
if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
//this will close the form but will keep application open if your
//application type is "console" in the properties of the project
this.Close();
}
For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.
Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:
private void button1_Click(object sender, EventArgs e)
{
Settings newSettingsWindow = new Settings();
if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
{
newSettingsWindow.Close();
}
}
send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.
public class DialogSettingsCancel
{
WindowSettings parent;
public DialogSettingsCancel(WindowSettings settings)
{
this.parent = settings;
}
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
this.parent.Close();
this.Close();
}
}
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
There are different methods to open or close winform.
Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed.
Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Form.Hide()
Application.Exit()
Some methods to Open/Start a form
Form.Show()
Form.ShowDialog()
Form.TopMost()
All of them act differently , Explore them !

Categories