2013-04-15 256 views
-2

我写此代码只选择PDF文件,但它不工作打开文件对话框

OpenFileDialog fd = new OpenFileDialog(); 
fd.ShowDialog(); 
fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; 
+7

尝试调用之前设置过滤器'的ShowDialog()'。之后设置将不会按预期工作。 –

回答

11

您需要打开该对话框之前设置Filter第一。

OpenFileDialog fd = new OpenFileDialog(); 
fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; //this should be before 
fd.ShowDialog(); 
1

哈比卜有正确的答案,但我觉得我想补充一点,你应该检查ShowDialog的响应,以确保用户没有取消对话框。如果他们在不选择文件的情况下取消对话框,则OpenFileDialog将会说文件名是“”,这在您的应用程序的其余部分中不会有用。

OpenFileDialog fd = new OpenFileDialog(); 
fd.Filter = "PDF Files(*.pdf)|*.pdf"; 
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
{ 
    // Do stuff here 
} 
else 
{ 
    // The user cancelled the request to select a PDF 
} 

希望这有助于