如何从C#中的应用程序窗口返回标签值?

时间:2015-10-25 16:48:01

标签: c# .net winforms

所以我用C#编写了windows应用程序。

我想选择一个文件夹并在该目录中进行一些搜索。问题是我无法将此路径提取到字符串变量。

这是从浏览文件夹窗口中检索folderPath的方法。 (在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是我的目录之路。

现在我尝试创建方法:

    public static string getLabelPath()
    {
        return this.labelPath.Text;
    }

在我的主程序中:

    string basePath = Form1.getLabelPath();

但由于Keyword 'this' is not valid in a static property, static method, or static field initializer ...\Form1.cs 37

,我不能这样做

如何返回此labelPath.Text值?我相信我可以调用类似myform.labelpath的东西;如果我只引用Form1对象,但在我的程序中使用以下命令初始化Windows应用程序:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

只需new Form1();not Form1 myform= Form1();。我不知道如何以正确的方式做到这一点。

2 个答案:

答案 0 :(得分:1)

我认为您应该删除static关键字:

public string getLabelPath()
{
    return this.labelPath.Text;
}  

并使用Form个实例:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Form1 form = new Form1();
    Application.Run(form);
}

或者您创建一个静态实例:

static Form1 form;
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    form = new Form1();
    Application.Run(form);
}

然后你可以拨打string basePath = form.getLabelPath();

答案 1 :(得分:1)

您是否考虑过直接使用Main()中的OpenFileDialog?

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