'How can I show/hide form with checkbox?
Sorry, I am new to C# and am unsure what I am doing wrong.
Here is the code I am using:
private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
{
frmSmallMenu sm = null;
if (chkSmallMenu.Checked)
{
if (sm is null || sm.IsDisposed)
{
sm = new frmSmallMenu();
}
sm.Show();
}
else
{
MessageBox.Show("close");
sm?.Close();
}
}
The window will open but when I uncheck the box nothing happens and I have no idea why. I have tried looking for an answer but nothing has worked for me.
Solution 1:[1]
This modification of your code would probably do what you want by first looking whether the other Form is already running or not:
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// The following `uselessField ` is a `field`. See also https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property
/// `(Since it is `unused`, you would get a CS0169 Warning in the "Error List" window)
private int uselessField;
/// <summary>
/// **Event handler** of the "chkSmallMenu" `CheckBox` control on your `Form`.
/// (You would probably get an IDE1006 Info in your "Error List" window because
/// the control name and/or the event handler name respectively, starts with a lower case
/// https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/naming-rules)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
{
// the following `sm` is a `variable`. See also https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property
var sm = Application.OpenForms.OfType<frmSmallMenu>().FirstOrDefault();
// the following `Checked` **property** belongs to the WinForms Checkbox class and `IsDisposed` belongs to the other `Form`
if (chkSmallMenu.Checked)
{
if (sm?.IsDisposed != true)
{
sm = new frmSmallMenu();
}
sm.Show();
}
else
{
MessageBox.Show("close");
sm?.Close();
}
}
}
}
Solution 2:[2]
This fixed my issue:
frmSmallMenu sm = new frmSmallMenu();
private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
{
if (chkSmallMenu.Checked == true)
{
sm.Show();
}
else
{
MessageBox.Show("close");
sm.Hide();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Elikill58 |
