Hi all,
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
Hi all,
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
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.
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
}
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
}
}
}
Well I also have checkbox on another form and I want to get that value to my main form, but the problem is that no matter whenever its checked or not, it returns me false.
CODE:
// on Form2.cs, which is named Configuration
public bool _continues;
public bool continues
{
get { return _continues; }
set { _continues = cBox_interval.Checked; }
}
// on Form1
private void button1_Click(object sender, EventArgs e)
{
Configuration _conf = new Configuration(); // calling second Form
bool _continues = _conf.continues;
MessageBox.Show(_continues.ToString());
}
and by default I even setted *cBox_interval.Checked = true* and messagebox still returns false