Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - How to enable button in Form 1 from Form 2 using public get set?

I have two buttons in Form 1, one is "ShowForm2" button and one is "button1" button.

Button 1 is disable by default. And when I click "ShowForm2" button, Form 2 will show.

PrntScn of my form 1

So, what I want is, when I click the "button2" in form 2, it will enable the "button1" in form 1.

enter image description here

So, I try to code like this in my form2 class:

public partial class Form2 : Form
{
    bool enable_form1_button1;
    public bool Enable_form1_button1
    {
        get { return this.enable_form1_button1; }
        set { this.enable_form1_button1 = value; }
    }
    public Form2()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        enable_form1_button1 = true;
    }
}

Then in my Form1 class, I am expecting to get the "enable_form1_button1 = true" to pass into form 1 and enable my form 1 button1. But how to do this?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btb_Showfrm2_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();
        button1.Enabled = frm2.Enable_form1_button1; // I put it here, and it just does not seems right
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well what you can do is, expose the button as a property and send a reference of your current form to the form that needs to take control:

Form1

public partial class Form1 : Form
{        
    public Button BtnShowForm2
    {
        get { return btnShowForm2; }
        set { btnShowForm2 = value; }
    }

    private void btnShowForm2_Click(object sender, EventArgs e)
    {
        // pass the current form to form2
        Form2 form = new Form2(this);
        form.Show();
    }
}

Then in Form2:

public partial class Form2 : Form
{
    private readonly Form1 _form1;

    public Form2(Form1 form1)
    {
        _form1 = form1;
        InitializeComponent();
    }

    private void btnEnabler_Click(object sender, EventArgs e)
    {
        // access the exposed property here <-- in this case disable it
        _form1.BtnShowForm2.Enabled = false;
    }
}

I hope this is what you're looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...