FolderBrowserDialog Question

G

Guest

Hi there!

I have a form with a button and a label.

Can anyone offer some insight as to why the following code snippet gives me
the following error: "Use of unassigned local variable 'path2'? If I remove
the variable all together and assign the label1.text = dialog.SelectedPath
then the code works but I don't understand why. I hope someone can shed some
light on the subject. Thanks.

Sean Campbell

private void button1_Click(object sender, EventArgs error)
{
string path2;
try
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowNewFolderButton = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
path2 = dialog.SelectedPath;
}

label1.Text = path2;
}
 
C

C.C. \(aka Me\)

If dialog.ShowDialog() != DialogResult.OK then path2 never gets initialized.

To fix it all you have to do is change

string path2;

to

string path2 = "";

That way path2 has been initialized.

The other option is to move the label1.Text=path2 line inside the if()
statement since you probably only want to set the Text if they click Ok
anyway?
 

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