Prometheus
Prometheus

Reputation: 2017

FileName in OpenFileDialog appears empty

I have two radio buttons and a regular button - button2.

I've created an if else statement that checks which of the radio buttons is clicked and accordingly preforms a given task. In particular, if:

This is my attempt:

    {

        if (radioButton1.Checked == true)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "PDF|*pdf";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.Show();
                axAcroPDF1.src = ofd.FileName;
            }

            textBox1.Text = ofd.FileName;

            MessageBox.Show(ofd.FileName);
        }


        else if (radioButton2.Checked == true)
        {
            OpenFileDialog ofd3 = new OpenFileDialog();
            ofd3.Filter = "PDF|*pdf";
            textBox1.Text = ofd3.InitialDirectory + ofd3.FileName;

            if (ofd3.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.Show();
            }
        }

        else if (radioButton2.Checked == false & radioButton1.Checked == false)
        {
            MessageBox.Show("Please select a processing option");
        }

        else
        {
            MessageBox.Show("Error.");
        }

    }

The issue is that I can't extract the FileName string in: textBox1.Text = ofd.FileName;

Basically, this returns an empty string. I'm not sure how this is possible, when in fact the axAcroPDF1.src successfully opens the selected pdf.

Any ideas?

Upvotes: 0

Views: 1065

Answers (2)

Avinash Avate
Avinash Avate

Reputation: 11

//Try this one    
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.src = ofd.FileName;
                axAcroPDF1.Show();
                textBox1.Text = ofd.FileName;
            }

Upvotes: 1

Bijan Rafraf
Bijan Rafraf

Reputation: 387

It is the ofd.ShowDialog() method which populates the ofd.FileName property.

Following the logic of your code:

For checkbox 1, you do the right thing to check the appropriate return of ofd.ShowDialog() before you access your axAcroPDF1 but there is no check that the user selected a file before you display the name in the checkbox.

For the checkbox 2 scenario, you are trying to access the ofd3.FileName before it is set by running the ofd3.ShowDialog() method.

The crucial point here is that ofd3.ShowDialog() is the point in your code where the dialog pops for the user.

You will want to move all of your calls to ofd.FileName and ofd3.FileName inside their respective if checks on the dialog.

Upvotes: 1

Related Questions