首页 > 解决方案 > 当前上下文中不存在名称“filePath”

问题描述

我正在尝试将一个变量传递到另一个私有 void 中。

private void button2_Click(object sender, EventArgs e)
{


    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        openFileDialog.InitialDirectory = "c:\\";
        openFileDialog.Filter = "All Files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;

        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            //Get the path of specified file
           var filePath = openFileDialog.FileName;

        }
    }
}


private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(filePath);
}

问题:

如何将变量 filePath 传递到另一个私有 void?

电流输出

当前上下文中不存在名称“filePath”

标签: c#

解决方案


您的变量当前具有本地范围,您需要将其设为成员变量。

// I've made the assumption you're creating a Windows Forms application.
public partial class YourForm : Form
{
    string filePath;

    public YourForm()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //Get the path of specified file
                filePath = openFileDialog.FileName;
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(filePath);
    }
}

推荐阅读