简体   繁体   English

如何在C#中从子窗体调用父窗体方法?

[英]How to call Parent Form method from Child Form in C#?

I have a parent form with 1 method to refresh the panel content called resetPanel() . 我有一个具有1种方法的父窗体,用于刷新面板内容,称为resetPanel() I also have a button in the parent form. 我在父表单中也有一个按钮。 If I click the button, a new form opens up. 如果单击按钮,将打开一个新表格。 I will do some changes and click on save. 我将做一些更改,然后单击保存。 The content gets saved in the database and the child form closes. 内容将保存在数据库中,并且子窗体关闭。 Now the parent form will be displayed. 现在将显示父表单。

I want to call the resetPanel() method now, so that the panel shows the updated values. 我现在想调用resetPanel()方法,以便面板显示更新的值。 How can I achieve this? 我该如何实现?

If your child form is a dialog one, you can just check the form's dialog result : 如果您的子窗体是对话框 ,则只需检查窗体的对话框结果即可

// Do not forget to release resources acquired: 
// wrap IDisposable into using(..) {...}
using (Form myChildForm = new MyChildForm()) {
  //TODO: If you want to pass something from the main form to child one: do it

  // On any result save "Cancel" update the panel
  if (myChildForm.ShowDialog() != DialogResult.Cancel) 
    resetPanel();
}

In case your child from is not a dialog you can pass this into child form as reference to main one: 如果你的孩子是不是一个对话框 ,你可以通过this成子窗体作为参考主要原因之一:

  Form myChildForm = new MyChildForm(this);

  myChildForm.Show(); // <- Just show, not ShowDialog()

  ...

  private MyMainForm m_MainForm;

  public MyChildForm(MyMainForm form) {
    m_MainForm = form;
  }

  private void save() {
    //TODO: Save to database here

    // Main form update
    if (!Object.ReferenceEquals(null, m_MainForm))
      m_MainForm.resetPanel(); // <- resetPanel should be public or internal method
  }

  private saveButton_Click(object sender, EventArgs e) {
    save();
  }

After you close your Form2 , you can call the ResetPanel method: 关闭Form2 ,可以调用ResetPanel方法:

Form2 f2 = new Form2();
f2.ShowDialog();
resetPanel();  // <-- this will be executed when you close the second form

for Eg ur Parent Form Name If form Form1 and child Form Name as Form2 goto ur Child form Designer page Change it Access Modifier as Public 用于例如父表单名称,如果表单Form1和子表单名称为Form2,请转到子表单设计器页面将其更改为公共访问修饰符

and from what ever method you want Call 以及您想使用的任何一种方法

Form2 f2=new Form2();
f2.Show();
.//from here on you can write your concerned code

If your resetPanel method is doing a database call, you quite possibly can avoid it. 如果您的resetPanel方法正在执行数据库调用,则很有可能避免它。 Although this will not get any data that was being updated by another user in your application. 尽管这不会获得您的应用程序中的另一个用户正在更新的任何数据。 Just modified code from another answer of mine for your needs. 只是根据您的需要修改了我的另一个答案中的代码。 This is just a sample: 这只是一个示例:

public class ParentForm : Form
{
    Button openButton = new Button();

    public ParentForm()
    {
        openButton.Click += openButton_Click;
    }

    void openButton_Click(object sender, EventArgs e)
    {
        ChildForm childForm = new ChildForm();
        childForm.OKButtonClick += childForm_OKButtonClick;
        childForm.ShowDialog();
    }

    void childForm_OKButtonClick(object sender, MyEventArgs e)
    {
        // Use properties from event args and set data in this form
    }

}

public class ChildForm : Form
{
    Button okButton = new Button();
    TextBox name = new TextBox();
    TextBox address = new TextBox();

    public event EventHandler<MyEventArgs> OKButtonClick;

    public ChildForm()
    {
        okButton.Click += okButton_Click;
    }

    void okButton_Click(object sender, EventArgs e)
    {
        try
        {
            bool saveSucceeded = false;

            // Try saving data here

            if (saveSucceeded)
            {
                if (OKButtonClick != null)
                {
                    MyEventArgs myEventArgs = new MyEventArgs();

                    // Just get updated data from screen and send it to another form
                    myEventArgs.Name = name.Text;
                    myEventArgs.Address = address.Text;

                    OKButtonClick(sender, myEventArgs);
                }

                Close();
            }
            else
            {
                MessageBox.Show("Data could not be saved.");
            }
        }
        catch (Exception ex)
        {
            // Perform proper exception handling
        }
    }
}

public class MyEventArgs : EventArgs
{
    public string Name
    {
        get;
        set;
    }

    public string Address
    {
        get;
        set;
    }
}

Try to set the Save button in your child Form to DialogResult.Ok and then make the Save button as the AcceptButton for child Form. 尝试将child Form的“ Save按钮设置为DialogResult.Ok ,然后将“保存”按钮作为子窗体的AcceptButton And then test if the result if it the user press that Save Button. 然后,如果用户按下该保存按钮,则测试结果是否正确。 Programmatically it could look like this: 以编程方式,它看起来可能像这样:

Form2 chidForm = new Form2();
childForm.btnSave.DialogResult = DialogResult.Ok
childForm.AcceptButton = childForm.btnSave
if (childForm.ShowDialog() == DialogResult.Ok)
{
  resetPanel();
}

Now, I assume here that your Save button in Child Form is named btnSave . 现在,我在这里假设您在Child Form中的Child Form Save按钮名为btnSave

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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