OpenFileDialog用于文件选择 [英] OpenFileDialog for file selection
问题描述
您好,
我有一个带文件名的字段,我希望当我点击该字段时,文件选择窗口(资源管理器)会被打开然后选择所需的文件(必须是xls或xlsx文件)。
但是当我点击该字段时,它会打开进行编辑,没有别的。
,我有以下说明:
this .bomNameFld.Click + = new System.EventHandler( this .bomNameFld_Click);
和方法,使用以下代码
private void bomNameFld_Click(object sender,EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
string file = openFile.FileName;
bomNameFld.Text = file;
}
我也试过使用Mouseclick和MouseEventhandler,结果是一样的。
任何人都可以帮助我吗?
提前谢谢。
David。
实例化openFile
后,必须调用ShowDialog方法对象。
private void bomNameFld_Click(object sender,EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog() ;
if(openFile.ShowDialog()== DialogResult.OK)
{
string file = openFile.FileName;
bomNameFld.Text = file;
}
}
另外,你应该检查从ShowDialog调用返回的布尔结果。如果用户单击确定,则返回True。如果用户单击取消,则返回False。
请参阅OpenFileDialog.ShowDialog方法 [ ^ ]
你已经创建了一个新的OpenFileDialog,但你没有做任何事情!
尝试添加DialogResult ds = openFile.ShowDialog();
并使用
if(ds == System.Windows.Forms.DialogResult.OK)在对结果做任何事情之前
Hello,
I have a field with a file name, and I want that when I click on that field, the file selection window (explorer) gets opened and thus select the desired file (must be an xls or xlsx file).
But when I click on the field, it opens for edit, nothing else.
in the design file, I have the following instruction:
this.bomNameFld.Click += new System.EventHandler(this.bomNameFld_Click);
and the method, with the following code
private void bomNameFld_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); string file = openFile.FileName; bomNameFld.Text = file; }
I have also tryed using Mouseclick and MouseEventhandler, but the result is the same.
Can anyone help me?
Thank you in advance.
David.
You have to call the ShowDialog method after you instantiate youropenFile
object.
private void bomNameFld_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); if( openFile.ShowDialog() == DialogResult.OK ) { string file = openFile.FileName; bomNameFld.Text = file; } }
Also, you should check the Boolean result returned from the call to ShowDialog. If the user clicks OK, then True is returned. If the user clicks Cancel, then False is returned.
See OpenFileDialog.ShowDialog Method[^]
You''ve created a new OpenFileDialog but you''re not doing anything with it!
Try addingDialogResult ds = openFile.ShowDialog();and using
if(ds == System.Windows.Forms.DialogResult.OK)before you do anything with the result
这篇关于OpenFileDialog用于文件选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!