如何在另一个事件中使用一个事件

时间:2014-01-08 15:59:36

标签: c#

我需要在另一个事件中使用一个事件。我是初学者,我不知道该怎么做。我想在第二个事件中使用第一个事件。

//第一个事件

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);
        }
    }

}

//第二个事件

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;
}

3 个答案:

答案 0 :(得分:7)

将该代码移动到单独的函数,然后在两个事件处理程序中调用该函数。

答案 1 :(得分:3)

您可以在this.saveAsToolStripMenuItem_Click(null, null)方法中调用Form1_FormClosing(因为实际上并未使用参数)。但是,我强烈建议将保存逻辑重构为一个单独的方法,并在适当的时候调用它,如下所示:

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;
   }
}

答案 2 :(得分:0)

今天,只需将第一个调用为此类函数

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;
}

明天,请阅读有关文档/视图,模型/视图/控制器,模型/视图/ ViewModel的博客/书籍/文章。