[英]How do I call other event methods?
private void save(object sender, EventArgs e)
{
if (File.Exists(fileLabel.Text))
{
// this will save in the debug folder unfortunately
FileStream outputFileStream = new FileStream(fileLabel.Text, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
// writing block (too long code)
writer.Close();
outputFileStream.Close();
}
else
{
saveAs(); // no overload
}
}
So what I'm trying to do is if a user presses Save
they will save the file without the dialog. 因此,我要尝试执行的操作是,如果用户按下“ Save
他们将保存文件而不显示对话框。 This code checks if the file exists to save. 此代码检查文件是否存在要保存。 If it doesn't exist it will redirect to the saveAsDialog
method. 如果不存在,它将重定向到saveAsDialog
方法。
private void saveAs(object sender, EventArgs e)
{
// code is similar (it works fine if user clicks the menu strip)
}
However, when I call the saveAs()
method it will not overload. 但是,当我调用saveAs()
方法时,它不会过载。 Now I've never called event handlers in my Form1
class so I wouldn't know how to use it. 现在,我从未在Form1
类中调用事件处理程序,因此我不知道如何使用它。 All the handlers are from double-clicking the form design. 所有处理程序均来自双击表单设计。
So what parameters do I have to put on the saveAs()
method call if I want it to do the same thing as if the user selected it from the menu strip? 因此,如果我希望它执行与用户从菜单栏中选择它相同的操作,我必须在saveAs()
方法调用上添加哪些参数?
尝试以下操作触发事件:
saveAs(this, EventArgs.Empty)
传递保存参数:
saveAs(sender, e);
在某个地方使用一种方法建议将代码重构为可以在任何地方使用的通用方法。
write a Method
using the code
of your save
event 使用save
事件的code
编写Method
void saveOrSaveAs()
{
if (File.Exists(fileLabel.Text))
{
// this will save in the debug folder unfortunately
FileStream outputFileStream = new FileStream(fileLabel.Text, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
// writing block (too long code)
writer.Close();
outputFileStream.Close();
}
else
{
saveAs(); //If You have already written code for saveAs() method.
}
}
And Call
this method in both events
as 而Call
在这两个这种方法events
作为
private void save(object sender, EventArgs e)
{
saveOrSaveAs();
}
Again call
this method
in your saveAs
Event
. 再次在saveAs
Event
call
此method
。
private void saveAs(object sender, EventArgs e)
{
saveOrSaveAs();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.