C# How can I check to see if a checkbox is checked on another form?
Question
I'm using C# and I'd like to check to see if a checkbox on the main form is checked and if so run some code, the problem is I'm in a class file (file with no form, is class file correct?). What is the easiest way to do this?
Thanks Jamie
Solution
The best option is to create a boolean
property on the Form that exposes the Checked
value of the CheckBox
.
public bool OptionSelected
{
get { return checkBox.Checked; }
set { checkBox.Checked = value; } // the set is optional
}
OTHER TIPS
You need a reference to the form, and the form has to expose the checkbox (or a property which consults the checkbox).
There's no difference between UI programming and non-UI programming in this respect. How would ask for the Name
property of a Person
instance from a different class? You'd get a reference to the instance, and ask for the relevant property.
So you definitely need a reference to the form, and then it's one of:
bool checked = form.IsAdultCheckbox.Checked;
bool checked = form.IsAdult;
(Where the IsAdult
property would return someCheckbox.Checked
.)
The actual property names may be wrong here (e.g. Checked
may not return a bool
) but I hope you get the idea.
Can you define an interface with a property, have the form implement the interface and return true if the checkbox is checked, and pass an instance of this interface to your class?
For example:
interface IMyFormFlag
{
bool IsChecked { get; }
}
public class MyForm : Form, IMyFormFlag
{
CheckBox chkMyFlag;
bool IsChecked { get { return chkMyFlag.Checked; } }
}
public class MyObject
{
public void DoSomethingImportant(IMyFormFlag formFlag)
{
if (formFlag.IsChecked)
{
// do something here
}
}
}
Personally, I don't like using set or get. I did it like this:
if (checkBox.IsChecked.Equals(true))
{
//insert code here
}
you can use this it works fine for me
if (Convert.ToBoolean(CheckBox1.IsChecked))
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}