将所选对话框项目转换为另一个按钮方法

时间:2015-05-23 05:01:56

标签: c# .net filedialog

所以我正在编写一个Windows窗体应用程序,用户将从他的计算机中选择一个xml文件(使用文件对话框),当他点击保存按钮时,它应该保存在数据库中。但是我对如何将所选项目添加到保存按钮方法感到有点迷失。以下是我的btnChooseFile_click

private void btnChooseFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Multiselect = false;
        dlg.Filter = "XML documents (*.xml)|*.xml|All Files|*.*";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            tbxXmlFile.Text = dlg.FileName;
            XmlDocument invDoc = new XmlDocument();
            invDoc.Load(dlg.FileName);
            ....
            ....
        }
    }

以下是我的btnStore_click

  private void btnStore_Click(object sender, EventArgs e)
    {
        try
        {
            string cs = @"Data Source=localhost;Initial Catalog=db;integrated security=true;";
            using (SqlConnection sqlConn = new SqlConnection(cs))
            {
                DataSet ds = new DataSet();
                ds.ReadXml("This is where I want to get the selected file");
                ....
                ....
            }
        }
    }

那我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您可以使用私有成员变量

private String filename = null;

private void btnChooseFile_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Multiselect = false;
    dlg.Filter = "XML documents (*.xml)|*.xml|All Files|*.*";

    if (dlg.ShowDialog() == DialogResult.OK)
    {
        tbxXmlFile.Text = dlg.FileName;
        XmlDocument invDoc = new XmlDocument();
        invDoc.Load(dlg.FileName);
        ....
        ....
        this.filename = dlg.FileName;
    }
}

private void btnStore_Click(object sender, EventArgs e)
{
    try
    {
        string cs = @"Data Source=localhost;Initial Catalog=db;integrated security=true;";
        using (SqlConnection sqlConn = new SqlConnection(cs))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(this.filename);
            ....
            ....
        }
    }
}