显示窗体关闭和打开时选择的文件名。 [英] To display the file-name that was chosen when the form is closed and opened.

查看:70
本文介绍了显示窗体关闭和打开时选择的文件名。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想在表单关闭然后打开后在文本框中显示文件名。我有一个带有2个表单的应用程序。我可以从表单1打开表单2并关闭它。在表单2中我有一个文本框,在我浏览文件并选择它之后出现文件名。但是当我关闭文件并打开它时,文本框是空的。我试图在form2类中使用公共字符串变量并在加载表单时使用该字符串但它显示空文本框。如何保留文件名直到应用程序关闭。

Hi i wanted to display the file name inside a textbox after the form is closed and then opened.I have an application with 2 forms.I can open Form 2 from form 1 and close it also .In Form 2 i have a textbox where the file name appears after i browse a file and select it .But when i close the file and open it the textbox is empty.I tried to use a public string variable within the form2 class and use that string while i load the form but it shows empty textbox .How could i retain the file-name till the application is closed .

推荐答案

使用静态类代替表单之间共享的数据。让上面的代码相同。使用Project-> Add Class ..添加新类。然后通过在 class 之前添加 static 来使类静态化。然后添加FileName变量,该变量应该是public和static。



让班级名称为共享。该课程应如下所示:



Use static classes instead for data shared between forms. Let the above code be the same. Add a new class using "Project->Add Class..". Then make the class static by adding static before class. Then add the FileName variable which should be both public and static.

Let the class name be "Shared". The class should look like the following:

public static class Shared
{
     public static string FileName;
}





然后在Form2的构造函数中更改



Then in the constructor of Form2 change

this.textBox1.Text = Filename1;



to


to

this.textBox1.Text = Shared.FileName;





然后在方法button1_Click中更改:



And then in the method "button1_Click" change:

Filename1 = openFileDialog1.FileName; 



to


to

Shared.FileName = openFileDialog1.FileName; 





删除这些不再需要的行:



Delete these lines as they are no longer needed:

private string Filename;
public string Filename1
{
get { return Filename; }
set { Filename = value; }
}


有很多方法可以在表单之间共享数据。您可以使用构造函数,属性和事件处理程序。



这里 [ ^ ]是一些示例代码,可以帮助您入门。
There are plenty of ways through which you can share data between forms. You can make use of constructors, properties and event handlers.

Here[^] is some sample code to get you started.


这篇关于显示窗体关闭和打开时选择的文件名。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆