0

I have some problems about savefiledialog c#, I have an unhandled exception of type System.NullReferenceException when I debug, this's code:

private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            switch (fileName)
            {
                case "":
                    {
                        saveFileDialog1 = new SaveFileDialog
                        {
                            Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
                            FileName = "MyPicture.bmp"
                        };
                        if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
                        fileName = saveFileDialog1.FileName;
                        bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
                    }
                    break;
                default:
                    {
                        bitmap.Save(fileName, ImageFormat.Bmp);
                    }
                    break;
            }

        }

here is my declare:

    private string fileName = "";
    private Bitmap bitmap;
    private Bitmap curBitmap;

here is my full code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //Bitmap


    //Graphics

    Graphics g;
    Pen p = new Pen(Color.Black, 8);
    Point start = new Point(0, 0);
    Point end = new Point(0, 0);
    bool drawing = false;

    //private int x1;
    //private int x2;
    //private int y1;
    //private int y2;
    //private int d1;
    //private int d2;
    private string fileName = "";
    private Bitmap bitmap;
    private Bitmap curBitmap;
    private Size fullSize;

    private void btnColorPicker_Click(object sender, EventArgs e)
    {
        //Get colors from colordialog
        DialogResult r = colorDialog1.ShowDialog();
        if (r == DialogResult.OK)
        {
            p.Color = colorDialog1.Color;
        }

    }


    private void PanelDrawing_MouseUp(object sender, MouseEventArgs e)
    {
        drawing = false;
    }

    private void PanelDrawing_MouseMove(object sender, MouseEventArgs e)
    {

        if (drawing && !earaser)
        {
            p.Width = PenSize.Value;
            p.Color = colorDialog1.Color;
            end = e.Location;
            g = PanelDrawing.CreateGraphics();
            g.DrawLine(p, start, end);
            PanelDrawing.Cursor = Cursors.HSplit;
        }
        else if (drawing && earaser)
        {
            end = e.Location;
            g = PanelDrawing.CreateGraphics();
            g.DrawLine(p, start, end);
            PanelDrawing.Cursor = Cursors.Cross;
        }
        else if (!drawing)
        {
            PanelDrawing.Cursor = Cursors.Default;
        }
        start = end;
    }

    private void PanelDrawing_MouseDown(object sender, MouseEventArgs e)
    {
        start = e.Location;
        if (e.Button == MouseButtons.Left)
        {
            drawing = true;
        }
    }

    private void PenSize_Scroll(object sender, EventArgs e)
    {
        p.Width = PenSize.Value;
        label1.Text = "" + PenSize.Value;
    }

    bool earaser = false;

    private void btnEaraser_Click(object sender, EventArgs e)
    {
        p.Color = Color.White;
        p.Width = 10;
        earaser = true;
    }

    private void btnBrush_Click(object sender, EventArgs e)
    {
        earaser = false;
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        g.Clear(PanelDrawing.BackColor);
    }

    private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(fileName))
        {
            saveFileDialog1 = new SaveFileDialog
            {
                Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
                FileName = "MyPicture.bmp"
            };

            if (saveFileDialog1.ShowDialog() != DialogResult.OK)
                return;

            fileName = saveFileDialog1.FileName;
            bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
        }
        else
        {
            bitmap.Save(fileName, ImageFormat.Bmp);
        }

    }
    private void Form1_Load(object sender, EventArgs e)
    {
        fullSize = SystemInformation.PrimaryMonitorMaximizedWindowSize;
        bitmap = new Bitmap(fullSize.Width, fullSize.Height);
        g = Graphics.FromImage(bitmap);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.Clear(BackColor);
    }


}
  • What do you suppose will happen if `fileName` is `null` (at the time of the `switch (fileName)` statement)? – Alex May 08 '15 at 01:25
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Nathan Tuggy May 08 '15 at 01:50
  • here is my declare: private string fileName = ""; private Bitmap bitmap; private Bitmap curBitmap; private Size fullSize; – Jack Wilson May 08 '15 at 01:51
  • 1
    This is really an abuse of a switch statement and should be changed out for an `if`. Check it like `if (string.IsNullOrWhiteSpace(fileName)) { ... }`. – Ron Beyer May 08 '15 at 01:52
  • Sorry, I dont understand why it continued to fail :( here exeption is: bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp); – Jack Wilson May 08 '15 at 02:01

4 Answers4

1

Since you haven't specified "where" the System.NullReferenceException is taking place. I will assume the following 2 cases

1.fileName is null. If that's the case add 1 more case (as shown below ) to your switch statement that takes null into consideration.

switch (fileName)
        {
            case  "":
            case null:
                {
                    saveFileDialog1 = new SaveFileDialog
                    {
                        Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
                        FileName = "MyPicture.bmp"
                    };
                    if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
                    fileName = saveFileDialog1.FileName;
                    bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
                }
                break;
            default:
                {
                    bitmap.Save(fileName, ImageFormat.Bmp);
                }
                break;
        }

2. You are using the same image stream, while saving, which was used to construct it. If that's the case use a new bitmap object as shown below.

 var newBitmap = new Bitmap(bitmap);
        switch (fileName)
        {

            case  "":
            case null:
                {
                    saveFileDialog1 = new SaveFileDialog
                    {
                        Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
                        FileName = "MyPicture.bmp"
                    };
                    if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
                    fileName = saveFileDialog1.FileName;
                    newBitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
                }
                break;
            default:
                {
                    newBitmap.Save(fileName, ImageFormat.Bmp);
                }
                break;
        }
Nathan
  • 1,303
  • 12
  • 26
1

probably it didn't catch the variable if its null or an empty string.

so instead of using switch statement, try doing it in If-Else statement.

xxxAcuGeekxxx
  • 133
  • 11
1

This isn't the place to use a switch statement. This is much easier re-written as an if:

private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
    if (string.IsNullOrWhiteSpace(fileName))
    {
        saveFileDialog1 = new SaveFileDialog
        {
            Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
            FileName = "MyPicture.bmp"
        };

        if (saveFileDialog1.ShowDialog() != DialogResult.OK) 
            return;

        fileName = saveFileDialog1.FileName;
        bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
    }
    else
    {
        bitmap.Save(fileName, ImageFormat.Bmp);
    }
}

The switch isn't appropriate just because its extremely confusing, and you have to test for multiple cases (null, empty string, whitespace). You can jam the code and make it work, but this is a lot more fool-proof.

Without seeing the rest of your code, its impossible to tell whether bitmap is going to be null or not. If its null, then calling .Save will result in a NullReferenceException. The best way to know why its null is to learn how to use the debugger. Set a breakpoint at the bitmap or where you utilize the bitmap to see why you aren't writing to it or creating the object in the first place.

Ron Beyer
  • 11,003
  • 1
  • 19
  • 37
0

Firstly, switch is not good way to handle strings I think.

string.IsNullorEmpty and string.IsNullorWhiteSpace might be useful for you.

Can you trace bitmap on your console? Are you sure you declared and initialized it correctly in your code?

This should solve any possibility:

private void saveToolStripMenuItem_Click(object sender,System.EventArgs e)
{
    var _Bitmap = new Bitmap(bitmap);
    //when we quit here we don't need this anymore; declaring it here helps with memory management
    if(_Bitmap == null)
        return;

    if(string.IsNullorEmpty(fileName)||string.IsNullorWhiteSpace(fileName)
    {
        Filter = @"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
        FileName = "MyPicture.bmp"
    }
    else
    {
        _Bitmap.Save(fileName,ImageFormat.Bmp);
    }
}

You assign bitmap on Form1_Load, try to do it on separate method and call it when you need it.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
İsmail Barış
  • 142
  • 1
  • 11