我有这段代码:
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public static string FolderSelect(string txtPrompt)
{
// Now, we want to use the path information to population
// our folder selection initial location
string initialCheckoutPathDir = ("C:\\");
System.IO.DirectoryInfo info =
new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
retPath = "";
DriveRecursion(retPath);
}
else
return "";
}
}
所以我有一个带按钮的WindowsForm。用户按下按钮,出现FolderBrowserDialog。一旦用户选择了一个驱动器,我希望表单(带按钮)也关闭。
我没有运气。有任何想法吗?语法将非常受欢迎。
答案 0 :(得分:3)
FolderSelect
返回DialogResult.OK
后,您需要致电this.close
。像这样:
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.empty;
//Now, we want to use the path information to population our folder selection initial location
string initialCheckoutPathDir = (@"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion(retPath);
result = retPath;
//Close this form.
this.Close();
}
return result;
}
修改强>
出于某种原因,您的FolderSelect
方法是静态的。您应该删除静态,以便它具有对表单的引用。
答案 1 :(得分:2)
您只需致电Close() 此外,您可以使用ShowDialog()而不是 Show()打开您的表单,并在关闭之前设置DialogResult:
DialogResult = FolderSelect.ShowDialog();
Close();
编辑:
你的 FolderSelect 方法应该是 void 。最好将 FolderSelect 对话框的结果保存到属性中。
答案 2 :(得分:0)
由于FolderSelect是静态的,因此您无权访问表单变量。所以,你有两个选择。
A)使FolderSelect成为实例方法。然后你可以这样做。关闭()注意你,这不是必要的,我只是为了清楚而把它放在那里。
B)从FolderSelect返回一个布尔值,若是真的,在按钮点击事件中,调用this.Close()
答案 3 :(得分:0)
在FolderSelect之后,输入this.Close();