我有NewForm
,当我点击新表单中的按钮时,我需要在主表单中执行某些操作。
public Newform()
{
InitializeComponent();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void dontsave_click(object sender, EventArgs e)
{
}
}
}
我有一个dontsave
按钮,当我点击并关闭newform时,我需要它来清除我的主窗体中的文本框。
答案 0 :(得分:1)
这将帮助您入门:
using System;
using System.Windows.Forms;
// Form1 code.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Form2 frm2 = new Form2(); // Instantiate your form2 object.
public Form1()
{
InitializeComponent();
frm2.Show(); // Show the form.
}
private void button_save_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.ShowDialog(); // This shows a 'Save' dialog.
if (saveDlg.ShowDialog() == DialogResult.OK) // Capture user input from the dialog.
{
// do some work here
}
}
private void dontsave_Click(object sender, EventArgs e)
{
frm2.ClearTextBox(frm2); // Call the 'ClearTextBox' function from form2.
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close(); // NOTE: Probably better to use Application.Exit() here.
}
}
}
//Form2 code.
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void ClearTextBox(Form form) // Pass a form as an overload.
{
textBox1.Text = ""; // Clear the textbox.
}
}
}
答案 1 :(得分:1)
创建NewForm时,您需要:
1)创建一个重载构造函数来接受您的父窗体 2)有一个公共财产,其中包含对您的父表单的引用,然后最终显示您的NewForm
然后当您按下“dontsave”时 - 只需引用父表单并清除文本框,并确保textbox属性是公共的或更优选的方法调用(不要从其他方式完全访问UI控件)形式!)
答案 2 :(得分:1)
我强烈建议不要盲目地将一个Form传递给另一个Form的构造函数。相反,暴露子表单的一些属性事件:
public Form1() {
var childForm = new ChildForm();
childForm.DontSave += // event handler
}
class ChildForm : Form {
public event EventHandler DontSave {
add { dontSaveButton.Click += value; }
remove { dontSaveButton.Click -= value; }
}
}
答案 3 :(得分:1)
在MainForm.cs
public partial class MainForm : Form
{
NewForm frm2;
public MainForm()
{
InitializeComponent();
frm2 = new NewForm();
frm2.Show();
frm2.dontSaveButton += new DontSaveButtonHandler(frm2_dontSaveButton);
}
void frm2_dontSaveButton()
{
textBox1.Clear();
frm2.Close();
}
}
在NewForm.cs
public delegate void DontSaveButtonHandler();
public partial class NewForm : Form
{
public event DontSaveButtonHandler dontSaveButton;
public NewForm()
{
InitializeComponent();
}
private void btnDontSave_Click(object sender, EventArgs e)
{
if (dontSaveButton != null)
{
dontSaveButton();
}
}
}
我猜我的回答应该是什么。使用委托是一种很好的做法。