[英]calling a method from another form c#
我有一個這樣的Mainform:
public partial class MainForm : Form
{
string FileName = "";
public MainForm()
{
InitializeComponent();
}
private void goToToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem ) sender;
switch (menuItem.Name.Replace("ToolStripMenuItem",""))
{
case "new":
MenuItemNew();
break;
case "open" :
MenuItemOpen();
break;
case "save":
MenuItemSave();
break;
case "saveAs" :
MenuItemSaveAs();
break;
case "exit" :
MenuItemExit();
break;
case "selectAll" :
MenuItemSelectAll();
break;
}
}
private void MenuItemSelectAll()
{
textBox.SelectAll();
}
private void MenuItemExit()
{
this.Close();
}
private void MenuItemSaveAs()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text Document |*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(sfd.FileName);
writer.Write(textBox.Text);
writer.Close();
}
}
private void MenuItemSave()
{
if (FileName == "")
{
MenuItemSaveAs();
}
else
{
StreamWriter writer = new StreamWriter(FileName);
writer.Write(textBox.Text);
writer.Close();
}
}
private void MenuItemOpen()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text Document|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
FileName = ofd.FileName;
StreamReader reader = new StreamReader(ofd.FileName);
textBox.Text = reader.ReadToEnd();
reader.Close();
}
}
private void MenuItemNew()
{
if (textBox.Text == "")
{
textBox.Text = String.Empty;
}
else
this.Show();
Newform sistema=new Newform();
sistema.ShowDialog();
}
}
和這樣的一個Newform:
public partial class Newform : Form
{
public Newform()
{
InitializeComponent();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void dontsave_click(object sender, EventArgs e)
{
}
private void save_Click(object sender, EventArgs e)
{
this.Hide();
}
}
在新表單中單擊保存時,我需要MenuItemSaveAs在主表單中打開。
第一
public void MenuItemSaveAs()
然后
private void save_Click(object sender, EventArgs e)
{
this.Hide();
((MainForm)Parent).MenuItemSaveAs()
}
假設您的表單是MainForm的子級。 如果不是,則需要將對MainForm的引用傳遞到表單的構造函數中,並將其保存在本地。 (還有一種方法可以始終找到當前程序的主要形式,但我認為這不是解決問題的一種優雅方法。)
旋律,問題確實出在設計上。 表單不應以另一種形式調用GUI元素。 這可能導致很難維護的“意大利面條”代碼。 如果它是您嘗試以這種方式操作的主要形式,則可以依靠它,但是它仍然違反了最佳實踐。 如果要嘗試以這種方式操作其他表格,則必須處理該表格不存在(尚未創建或已被處置)的可能性。
如果代碼需要操縱表單的GUI,則所述代碼應在該表單內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.