【问题标题】:Getting selected dialog item to another button method将选定的对话框项获取到另一个按钮方法
【发布时间】:2015-05-23 05:01:56
【问题描述】:

所以我正在编写一个 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");
                ....
                ....
            }
        }
    }

那我该怎么办呢?

【问题讨论】:

  • 只需将其存储在私有变量中
  • @NedStoyanov 当然,我真傻。谢谢!

标签: c# .net filedialog


【解决方案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);
            ....
            ....
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2019-06-18
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2014-03-11
    • 2020-09-10
    相关资源
    最近更新 更多