Can someone please check my understanding here and suggest fix

G

garyusenet

The following code was supplied by a kind poster as a solution to a
problem i was having. But it's not quite working. I have commented the
code myself below. Can you please read my comments to make sure what
i've said is correct to check my understanding of what is happening.

Also the problem i have is that the openfiledialog isn't being
displayed when i run the code, does anyone know why?


namespace MyNamespace
{
public partial class Form1 : Form

{
private void Form1_Load(object sender, EventArgs e)
{
string file; // create a new string variable
called file.
file = FileOpen(); // call the function FileOpen and
set file equal to the returned value.
}


private string FileOpen() //new function, that
returns a string result.
{
string file = null; //assign local file
variable.


//the following uses IF to execute the ShowDialog method of
openFileDialog1, and
//if when the dialog exits the DialogResult is OK - the
Filename selected is stored
//in the local file variable
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
file = openFileDialog1.FileName;
}


return file; //this passes the value of the local file
variable back to the calling Form1_Load
//method.
}
}
}
 
G

gary

Hello,

It looks like what you are trying to do is to open a file dialog and
return the name of the file chosen by the user. If this is the case,
then the following code will suffice...

string fileName = "";
OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
fileName = ofd.FileName;
}
 
G

garyusenet

Thankyou. I tried your code and now have the following: -

namespace MyNamespace
{
public partial class Form1 : Form

{
private void Form1_Load(object sender, EventArgs e)
{
string fileName = "";

OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
fileName = ofd.FileName;

}
}

}
}


But i still have the same problem, all i have when i run the program is
a blank form, and the open file dialog box isn't displayed.

Please advise,

Gary.
 
G

gary

Try cutting the code out of the form load handler and putting it in a
button click handler and see how you go. That code works for me in both
handlers so I'm not sure what your problem is.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top