简体   繁体   中英

Calling method in other class (Windows Form) in C#

I have two forms "Form1" and "Form2" now I want to call the method "change_lbl()" that exist in "Form1" from "Form2" but when I call the method in "Form2" it is not implemented and is unable to execute

Codes Form1:

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

    public void change_lbl()
    {
        lbl_form1.Text = "Its Done !";
    }

    private void btn_gofrm2_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();
    }
}

Codes Form2:

public partial class Form2 : Form
{
    Form1 frm1 = new Form1();
    public Form2()
    {
        InitializeComponent();
    }

    private void btn_form2_Click(object sender, EventArgs e)
    {
        frm1.change_lbl();
        this.Close();
    }
}

code is correct and method invokes correctly! you are creating and using a new instance of Form1 without showing it, but it looks you are expecting to see changes in default instance of Form that is using by Application and currently is open. to have the open instance of Form1 class:

Form1 myForm1=(Form1)Application.OpenForms["Form1"];

I would suggest you to take a look at this project. This might solve your problem. Basically when you call Form2 and click a button( I mean a Form2 button) then Form1 must 'capture' the event ie an event like Form2buttonClicked. Take a look at this article to know more. http://www.codeproject.com/Articles/17371/Passing-Data-between-Windows-Forms

This might be a little irrelevant but this might help you as well http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms

Create an EventHander in Form2 and subscribe to that event in Form1 . Work's fine

public partial class Form2 : Form
{
    public event EventHandler ButtonClicked;
    public Form2()
    {
        InitializeComponent();
    }

    private void btn_form2_Click(object sender, EventArgs e)
    {
        if(ButtonClicked != null);
           ButtonClicked(sender, new EventArgs());
        this.Close();
    }
}

Now in Form1 subscribe to the event and call change_lbl()

private void btn_gofrm2_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.ButtonClicked += (se,ev) => change_lbl();
    frm2.Show();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM