Reputation: 41
I need to use one event in another event. I'm beginner and I don't know how to do it. I want to use the first event in the second event.
//First event
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text Document(*.txt)|*.txt|All files(*.*)|";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}
//second event
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult rezult = MessageBox.Show("Sunteti sigur ca doriti sa iesiti din program !?",
"Aplication closing", MessageBoxButtons.YesNoCancel);
if (rezult == DialogResult.Yes)
{
//I want to use first event in this if,please help me;
e.Cancel = false;
}
else if (rezult == DialogResult.No)
{
e.Cancel = false;
}
else
e.Cancel = true;
}
Upvotes: 0
Views: 113
Reputation: 3685
For today, just call first one as a function like this
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult rezult = MessageBox.Show("Sunteti sigur ca doriti sa iesiti din program !?",
"Aplication closing", MessageBoxButtons.YesNoCancel);
if (rezult == DialogResult.Yes)
{
// call other event handler as a function, for it is one
saveAsToolStripMenuItem_Click(null, null);
e.Cancel = false;
}
else if (rezult == DialogResult.No)
{
e.Cancel = false;
}
else
e.Cancel = true;
}
And tomorrow, read a blog/book/article about Document/View, Model/View/Controller, Model/View/ViewModel.
Upvotes: 0
Reputation: 149058
You can just call this.saveAsToolStripMenuItem_Click(null, null)
in your Form1_FormClosing
method (since the parameters aren't actually used). However, I'd strongly recommend refactoring the save logic into a separate method, and invoking it where appropriate, like this:
private void Save()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text Document(*.txt)|*.txt|All files(*.*)|";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Save();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult rezult = MessageBox.Show("Sunteti sigur ca doriti sa iesiti din program !?",
"Aplication closing", MessageBoxButtons.YesNoCancel);
if (rezult == DialogResult.Yes)
{
this.Save();
e.Cancel = false;
}
else if (rezult == DialogResult.No)
{
e.Cancel = false;
}
else
e.Cancel = true;
}
}
Upvotes: 3
Reputation: 888167
Move that code to a separate function, then call that function in both event handlers.
Upvotes: 7