Sean Connelly Sean Connelly - 3 months ago 9
C# Question

How to change the background color in a rectangle in a winforms grid?

I am building a graph using the following code. I need to be able to change the color of any given rectangle by clicking on it with the mouse. I am, so far, unable to find a way to accomplish this.

Any ideas would be greatly appreciated.

int number;
public List<Rectangle> listRec = new List<Rectangle>();
Graphics g;

public CrochetPtrnDesign()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
number = int.Parse(textBox1.Text);
Rectangle rect = new Rectangle();
listRec.Clear();
rect.Size = new Size((pnlDesign.Width - 1) / number, (pnlDesign.Height - 1) / number);
for (int x = 0; x < number; x++)
{
rect.X = x * rect.Width;
for (int y = 0; y < number; y++)
{
rect.Y = y * rect.Height;
listRec.Add(rect);
}
}
}
catch
{
MessageBox.Show("Please enter a number...");
}
foreach (Rectangle rec in listRec)
{
g = pnlDesign.CreateGraphics();
Pen p = new Pen(Color.Black);
g.DrawRectangle(p, rec);
}
}

Answer

I found a way to accomplish this. Here is the code that I am using now. I will still have to build the color selection tool, but that is going to be the easy part, I think. All of your suggestions helped lead me to the solution. I thank you all.

private void pnlDesign_MouseClick(object sender, MouseEventArgs e)
{
    Point point = pnlDesign.PointToClient(Cursor.Position);
    SolidBrush blueBrush = new SolidBrush(Color.Blue);

    int listCount = 0;
    for (listCount = 0; listCount < number * number; listCount++)
    {
        if (listRec[listCount].Contains(point))
        {
            g.FillRectangle(blueBrush, listRec[listCount]);
        }
    }
}