user3756824
user3756824

Reputation: 107

How to store a drawn rectangle in an array?

I have a small program where I can draw a rectangle on a Panel. However, after it is drawn, I'd like to store it in a List array for later display. I tried to just pass it in a MouseButtonUp event, but it returns Null Reference Exception, as I think mouse is initially in Up state and thus the issue(?). Is there any way to achieve storing the drawn shapes?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GraphicEditor
{
public partial class Form1 : Form
{
    private bool _canDraw;
    private int _startX, _startY;
    private Rectangle _rectangle;
    private List<Rectangle> _rectangleList;

    public Form1()
    {
        InitializeComponent();


    private void imagePanelMouseDown(object sender, MouseEventArgs e)
    {
        _canDraw = true;
        _startX = e.X;
        _startY = e.Y;

    }

    private void imagePanelMouseUp(object sender, MouseEventArgs e)
    {
        _canDraw = false;
       // _rectangleList.Add(_rectangle); //exception
    }

    private void imagePanelMouseMove(object sender, MouseEventArgs e)
    {
        if(!_canDraw) return;

        int x = Math.Min(_startX, e.X);
        int y = Math.Max(_startY, e.Y);
        int width = Math.Max(_startX, e.X) - Math.Min(_startX, e.X);
        int height = Math.Max(_startY, e.Y) - Math.Min(_startY, e.Y);
        _rectangle = new Rectangle(x, y, width, height);
        Refresh();
    }

    private void imagePanelPaint(object sender, PaintEventArgs e)
    {
        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, _rectangle);
        }
    }




}
}

Upvotes: 1

Views: 1083

Answers (2)

Green Falcon
Green Falcon

Reputation: 836

You have not initialized _rectangleList. So whenever you use its object you get a null reference exception.

Upvotes: 2

Mark Cidade
Mark Cidade

Reputation: 100007

You need to initialize _rectangleList:

private List<Rectangle> _rectangleList = new List<Rectangle>();

Upvotes: 3

Related Questions