c# - 当前上下文中不存在名称“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”
解决方案
您的变量当前具有本地范围,您需要将其设为成员变量。
// 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);
}
}
推荐阅读
- reactjs - 打字稿:ts2307 找不到类型声明,甚至安装了@types/react
- docker - 如何在 Jenkins 中显示外部 URL 作为构建结果
- r - 如何在 sample.split 中使用对象作为因变量
- javascript - 如何在 Nodejs 中访问终端
- rust - 设计类型 MutexGuardRef
- jquery - laravel - 无法从模态获取数据ID
- r - 将 3D 数组转换为整洁的数据框?
- c# - WCF LocalChannel,在一个服务内调用一个服务,同一个应用,同一个机器
- javascript - 移动文本后不再反应
- sql - convert_timezone 对雪花 sql 中的 timestampdiff 没有意义