-->

how to i call a variable from the form.cs file to

2019-08-31 23:02发布

问题:

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);

This is my code I am geting one variable from

 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);  
            }  
        }  

Any help will be appreciated.

回答1:

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;

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;
        }
    }
}


回答2:

var di = new DirectoryInfo(Form1.dlg.SelectedPath);      
di.CopyTo(Form1.dlg2.SelectedPath, true); 

The problem with the above code is that you try to access member variables of a form instance as if it were a class member.

You write Form1.dlg.SelectedPath but Form1 is the name of your class and probably not of the instance.

Another error you probably encounter is that the compiler says that the member is inaccessible due to its protection level. This is because your members are not declared public (the dlg-variable). This is right, but instead of making it public, provide a property for accessing members of a class. This problem occurs if you try to access the member from another class (I thinK you try to do this).

public FolderBrowserDialog Dlg{
   get{return dlg;}
}

Better however for this is a solution like Marc Gravell posted, not providing the dialog but its selected value.