Kaitlyn
Kaitlyn

Reputation: 801

c# openFileDialog IndexOutofRange error

I have an issue getting a openFileDialog to even show.

Here is my current situation:

I have a WinForms program with multiple forms, but they all run in the same thread. Currently, I have two forms that has a saveFileDialog and openFileDialog each.

For the first form, which is the one that opens upon starting, both the saveFileDialog and openFileDialog works fine, but for the second form, the openFileDialog refuses to even open.

Here is the stack trace I am getting right now:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Windows.Forms.dll at System.Windows.Forms.OpenFileDialog.OpenFile()

Here is the code where the issue occurs:

private void loadScreenshotToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            bmpOpenFileDialog = new OpenFileDialog();
            bmpOpenFileDialog.Filter = "Bitmap|*.bmp;*.dib|Exchangable Image Format|*.exif|Icon|*.ico|JPEG|*.jpg;*.jpeg;*" +
    ".jpe;*.jfif|GIF|*.gif|PNG|*.png|All files|*.*";
            this.bmpSaveFileDialog.Title = "Load Screenshot";
            bmpOpenFileDialog.OpenFile();
        }
        catch (Exception ex)
        {
            MessageBox.Show("\nReport this error to the creator:\n\n" + ex);
            System.Diagnostics.Debug.WriteLine(ex.StackTrace);
        }
    }

If the user clicks ok, this would have been triggered:

private void bmpOpenFileDialog_FileOk(object sender, CancelEventArgs e)
    {
        Image tempIMG = Image.FromFile(bmpOpenFileDialog.FileName);
        oriBmp = new Bitmap(tempIMG);
        prntscrPictureBox.Image = oriBmp;
        saveScreenshotToolStripMenuItem.Enabled = true;
        zoomInToolStripMenuItem.Enabled = true;
        zoomOutToolStripMenuItem.Enabled = true;
        originalZoomToolStripMenuItem.Enabled = true;
        fullSizeToolStripMenuItem.Enabled = true;
        customToolStripMenuItem.Enabled = true;
        zToolStripStatusLabel.Text = "Zoom Level: " + zoomFactor.ToString("2F");
    }

Upvotes: 1

Views: 929

Answers (1)

Grant Winney
Grant Winney

Reputation: 66449

You haven't prompted the user to select a file... you need to show the OpenFileDialog.

...
bmpOpenFileDialog.ShowDialog();  // <-- you forgot this line
bmpOpenFileDialog.OpenFile();

Also, OpenFile() doesn't do much by itself. You're not doing anything with the Stream it creates.

Upvotes: 2

Related Questions