我如何从form.cs文件调用变量到program.cs文件 [英] how to i call a variable from the form.cs file to the program.cs file
问题描述
我在访问两个变量时遇到麻烦.我浏览了互联网,发现需要使用类似form.dlg.selectedpath
的名称来调用它,但是出现了三个错误.一个说form.dlg无法访问,另一个说需要对象引用.我还尝试访问另一个,它说表单不包含dlg2的定义.
I am having trouble accessing two of my variables. I have looked on the internet and found that I need to use something like form.dlg.selectedpath
to call it but I get three errors. One says form.dlg is inaccessible the next says an object reference is required. I also try to access another one and that says form does not contain definition for dlg2.
这是我想要插入变量的代码.
This is the code I want the variables in.
var di = new DirectoryInfo(Form1.dlg.SelectedPath);
di.CopyTo(Form1.dlg2.SelectedPath, true);
这是我的代码,我从
public partial class Form1 : Form
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (dlg.ShowDialog() == DialogResult.OK)
第二个变量从这里引用.
And the second variable is referenced from here.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg2 = new FolderBrowserDialog();
if (dlg2.ShowDialog() == DialogResult.OK)
//do whatever with dlg.SelectedPath
{
backgroundWorker1.RunWorkerAsync(dlg2.SelectedPath);
}
}
任何帮助将不胜感激.
推荐答案
字段不应该直接暴露出来;而是在表单上添加一个属性:
Fields should not really be directy exposed; instead add a property on the form:
public string FolderPath {
get { return dlg.SelectedPath; }
}
然后从您的表单实例进行访问:
Then access from your form instance:
string path = myFormInstance.FolderPath;
也-确保将dlg
与表格一起放置;实际上,个人我不会将其保留为一个字段-我会在一个小块中分配一个强大的字段,该小块创建,使用和配置对话框:
Also - make sure that dlg
is disposed with the form; in pact personally I wouldnt keep it as a field at all - I'd have a strong field that I assign in a small block that creates, uses and disposes the dialog:
public string FolderPath { get; private set; }
private void SelectPath() {
using(var dlg = new FolderBrowserDialog()) { // or whatever type
if(dlg.ShowDialog() == DialogResult.OK) {
FolderPath = dlg.SelectedPath;
}
}
}
这篇关于我如何从form.cs文件调用变量到program.cs文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!