WinForms raise event from another Form

2019-02-16 05:02发布

I have a main form named: MainForm and a child form named: ChildForm I want to fill ChildForm's textboxes and in MainForm_ButtonClick i want to fire ChildForm_ButtonClick event.

ChildForm:

public partial class ChildForm :Form
  {
        public delegate void delPassData(TextEdit text);

 private void button1_Click(object sender, EventArgs e)
    {
       string depart = "";

       MainForm mfrm = new MainForm();
       delPassData del = new delPassData(frm.funData);
       del(this.Item_CodeTextEdit);
    }
}

MainForm:

public partial class MainForm : Form
 {

 public void funData(TextEdit txtForm1)
    { 
        string ss = "";
        ss = txtForm1.Text;
        MessageBox.Show(ss);
    }

  private void NavigationPanelBtns_ButtonClick(object sender, ButtonEventArgs e)
    {
        switch (e.Button.Properties.Caption)
        {
            case "Save":
             // i want to call funData() here but i get an empty messageBox
            break;
        }
    }

}

2条回答
别忘想泡老子
2楼-- · 2019-02-16 05:56

Child form

public partial class ChildForm : Form
{
    public ChildForm()
    {
        InitializeComponent();
        MainForm.OnChildTextChanged += MainForm_OnChildTextChanged;
        MainForm.OnButtonClick += MainForm_OnButtonClick;
        bttn1.Visible = false;
    }

    void MainForm_OnButtonClick(object sender, EventArgs e)
    {
        this.bttn1.PerformClick();
    }

    void MainForm_OnChildTextChanged(string value)
    {
        this.textBox1.Text = value;
    }

    private void bttn1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("I am hide. But shows message");
    }

}

public class Bttn : Button
{
    public new void PerformClick()
    {
        this.OnClick(EventArgs.Empty);
    }
}

Create a Parent Form

public partial class MainForm : Form
{
    public delegate void OnMyTextChanged(string value);
    public delegate void ButtonClicked(object sender, EventArgs e);

    public static event OnMyTextChanged OnChildTextChanged;
    public static event ButtonClicked OnButtonClick;

    ChildForm frm = new ChildForm();

    public MainForm()
    {
        InitializeComponent();
        frm.Show();
    }

    public void button1_Click(object sender, EventArgs e)
    {
        OnChildTextChanged("this is new value");
        OnButtonClick(sender, e);
    }
}
查看更多
叛逆
3楼-- · 2019-02-16 06:06

To access a textbox in another form:

  1. Set Modifier property of the the textbox to public in child form.

  2. In main form, access the textbox by an object of the child form.

    Eg:

    obj.txtBox.Text="MyValue";
    

To access an event in another form:

  1. Set the event handling function to public.

  2. Invoke the function by passing null as parameters by the object of the form.

    Eg:

    obj.MyButton_Click(null, null);
    
查看更多
登录 后发表回答