user3756824 user3756824 - 5 months ago 33
C# Question

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()

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);

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



You need to initialize _rectangleList:

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