disabling a button on form 2 from form 1 with a checkbox

僤鯓⒐⒋嵵緔 提交于 2021-01-29 18:06:23

问题


I have two form objects: form1 and form2.

I have 1 button on form2 and a check box on form1. When the check box is checked, I want to show the button and when it is unchecked I want the button to be disabled. I know that in visual basic I did such a thing like this:

form2.button.visible = false

How would I do something like this in c# ?


回答1:


In general case (when Form1 and From2 instances are independent) you can do something like that. In Form2 implement a public property:

  public partial class Form2 {
    ...
    public Boolean IsMyButtonVisible {
      get {
        return myButton.Visible;
      } 
      set {
         myButton.Visible = value; 
      } 
    } 
    ...
  }

In Form1 on myCheckBox CheckedChanged find out Form2 instances and assign the property:

  public partial class Form1 {
    ...
    private void myCheckBox_CheckedChanged(object sender, EventArgs e) {
      foreach(Form f in Application.OpenForms) {
        Form2 form2 = f as Form2; 

        if (form2 != null)
          form2.IsMyButtonVisible = myCheckBox.Checked;
      }
    }
    ...
  } 


来源:https://stackoverflow.com/questions/26479548/disabling-a-button-on-form-2-from-form-1-with-a-checkbox

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