So I have written windows application in C#.
I want to select a file folder and do some searching in that directory. The problem is that I can't extract this path to a string variable.
This is method for retrieving folderPath from my browse folders window. (in public partial class Form1 : Form
)
private void folderPath_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
this.labelPath.Text = folderBrowserDialog1.SelectedPath;
// this piece of code works fine
}
}
this.labelPath.Text
is my path to directory.
Now I tried creating method:
public static string getLabelPath()
{
return this.labelPath.Text;
}
And in my main program:
string basePath = Form1.getLabelPath();
But I cannot do this, because of Keyword 'this' is not valid in a static property, static method, or static field initializer ...\\Form1.cs 37
How do I return this labelPath.Text value? I believe I could call something like myform.labelpath; if only I had reference to Form1 object, but in my program Windows Application is initialized using:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Just new Form1();
, not Form1 myform= Form1();
. I don't know how to do this the right way.
I think you should remove the static
keyword:
public string getLabelPath()
{
return this.labelPath.Text;
}
And use a Form
instance:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
Application.Run(form);
}
or you create a static instance:
static Form1 form;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new Form1();
Application.Run(form);
}
Then you can call string basePath = form.getLabelPath();
Have you considered just directly using OpenFileDialog from Main()?
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Title = "Please select a File to Blah blah bleh...";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;
// ... now do something with "fileName"? ...
Application.Run(new Form1(fileName));
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.