我有两个窗体,比如FORM1有个按钮是导入数据的。但是FORM2的按钮是实现数据导入的。
比如导入按钮的功能
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = this.openFileDialog1.FileName;
                StreamReader sr = new StreamReader(path, Encoding.Default);
                XmlSerializer xml = new XmlSerializer(typeof(AccountCollection));
                AccountCollection accColl = null;
                try
                {
                    accColl = (AccountCollection)xml.Deserialize(sr);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("被损坏的数据文件或不合法的数据格式,无法导入!!\n:" + ex.Message);
                    return;
                }
                finally
                {
                    if (sr == null)
                    {
                        sr.Close();
                    }
                }
      }
我想用FORM1窗体的那个按钮去实现FORM2那个按钮的功能。但是不用像FORM那样打那么多代码。用什么方法呢?
比如按FORM1按钮就等于按了FORM2按钮的意思。

解决方案 »

  1.   

    将导入功能写入From2
    public class Form2 : System.Windows.Forms.Form
    {
    public void button1_Click(object sender, System.EventArgs e)
    {
    this.ExportData();
    }
    public void ExportData()
    {
    if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
    {
    string path = this.openFileDialog1.FileName;
    StreamReader sr = new StreamReader(path, Encoding.Default);
    XmlSerializer xml = new XmlSerializer(typeof(AccountCollection));
    AccountCollection accColl = null;
    try
    {
    accColl = (AccountCollection)xml.Deserialize(sr);
    }
    catch (Exception ex)
    {
    MessageBox.Show("被损坏的数据文件或不合法的数据格式,无法导入!!\n:" + ex.Message);
    return;
    }
    finally
    {
    if (sr == null)
    {
    sr.Close();
    }
    }
    }} 
    }Form1:
    public class Form1 : System.Windows.Forms.Form
    {
    private void button1_Click(object sender, System.EventArgs e)
    {
    Form2 form2 = new Form2();
    form2.ExportData();
    }
    }