Best way to handle passing of Control.Checked state between forms

雨燕双飞 提交于 2019-12-23 04:17:08

问题


It's been a while since I've worked with Windows Forms applications. I have a Checkbox on the Main form and, based upon a certain condition, if the Second form needs to be opened to request additional data from the user, how should I pass (or get) back a message to the Main form from the Second form so I can tell whether or not it's okay to Check or Uncheck the Checkbox?

From what I can remember, I could use something like Pass by ref. Or is there a better way to accomplish this?


回答1:


One way to do this would be to use an event.

In your child form, declare an event to be raised upon specific user interaction, and simply "subscribe" to this event in your main form.

When you instantiate and call you child form, you'd do like this:

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.MyEvent += frm_MyEvent;
    frm.ShowDialog();
    frm.MyEvent -= frm_MyEvent;
}

private void frm_MyEvent(object sender, EventArgs e)
{
    textBox1.Text = "whatever"; //just for demo purposes
}

In your child form, you declare the event and raise it:

public event EventHandler MyEvent;

private void button1_Click(object sender, EventArgs e)
{
    if (MyEvent!= null)
        MyEvent(this, EventArgs.Empty);
}

Hope this helps




回答2:


Since you are showing the child form as a dialog, and the parent form doesn't need it until the form as closed, all you need to do is add a property with a public getter and private setter to the child form, set the value in the child form whenever it's appropriate, and then read the value from the main form after the call to ShowDialog.



来源:https://stackoverflow.com/questions/12976205/best-way-to-handle-passing-of-control-checked-state-between-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!