Click here to Skip to main content
15,891,670 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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:
C#
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.
Posted
Updated 13-Mar-13 3:49am
v3
Comments
[no name] 13-Mar-13 9:35am    
"it opens for edit, nothing else" and what is it that you expect it to do instead of "nothing else"?
Pheonyx 13-Mar-13 9:36am    
Can you explain your question please as it is unclear what you are trying to do.
Mike Meinz 13-Mar-13 9:44am    
When you say "it opens for edit, nothing else", do you mean that the Textbox control gets focus to allow you to type into it and the OpenFileDialog window is not displayed?
sjelen 13-Mar-13 11:59am    
Do not edit design file manually, it's auto generated whenever you change something in designer and you might loose your code.
Set your event handler from designer or from code in .cs file, never in .designer.cs

You have to call the ShowDialog method after you instantiate your openFile 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[^]
 
Share this answer
 
v4
Comments
fjdiewornncalwe 13-Mar-13 9:54am    
+5. (I just updated the openFile.ShowDialog to include the OK result check as that should always be done.) Cheers.
Mike Meinz 13-Mar-13 9:55am    
Thanks Marcus. I was just getting ready to add the if statement myself but you beat me to it.
You've created a new OpenFileDialog but you're not doing anything with it!
Try adding
DialogResult ds = openFile.ShowDialog();
and using
if(ds == System.Windows.Forms.DialogResult.OK)
before you do anything with the result
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900