[英]WinForms raise event from another Form
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. 我有一个名为:MainForm的主表单和一个名为:ChildForm的子表单。我想填写ChildForm的文本框,并在MainForm_ButtonClick中,我要触发ChildForm_ButtonClick事件。
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);
}
}
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;
}
}
} }
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);
}
}
To access a textbox in another form: 要以另一种形式访问文本框:
Set Modifier
property of the the textbox to public
in child form. 将文本框的“
Modifier
属性设置为子窗体形式的public
。
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: 要以其他形式访问事件:
Set the event handling function to public
. 将事件处理功能设置为
public
。
Invoke the function by passing null
as parameters by the object of the form. 通过将表单对象传递
null
作为参数来调用该函数。
Eg: 例如:
obj.MyButton_Click(null, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.