Teron Kee Teron Kee - 2 months ago 17
C# Question

An unhandled exception of type 'System.ArgumentException' occurred

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll , Additional information: The path is not of a legal form. Error only occurs after it's being pressed for the second time after closing the window .

Heres code:

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OpenFd = new OpenFileDialog();
OpenFd.Filter = "Images only. |*.jpg; *.jpeg; *.png; *.gif;";

DialogResult dr = OpenFd.ShowDialog();
pictureBox1.Image = Image.FromFile(OpenFd.FileName);
ItemUrl.Text = OpenFd.FileName;


}

Answer

You need to handle whether you selected an image or clicked "Cancel" on the FileDialog. Use this format instead:

        OpenFileDialog OpenFd = new OpenFileDialog();
        OpenFd.Filter = "Images only. |*.jpg; *.jpeg; *.png; *.gif;";

        if (OpenFd.ShowDialog() == DialogResult.OK) //You selected an image
        {
            pictureBox1.Image = Image.FromFile(OpenFd.FileName);
            ItemUrl.Text = OpenFd.FileName;
        }
        else
        {
            //You cancelled the operation
        }