Click here to Skip to main content
15,035,723 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanna know how to draw a rectangle on tablelayoutpanel in c# windows application. Although I use tablelayoutpanel.sendtoback(),it doesn't work. The rectangle is behind the tablelayoutpanel as usual.

private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
        {
            int row = 0;
            int verticalOffset = 0;
            Graphics surface = this.CreateGraphics();
            Pen p = new Pen(System.Drawing.Color.Turquoise,5);           
           
            foreach (int h in tableLayoutPanel1.GetRowHeights())
            {
                int column = 0;

                int horizontalOffset = 0;

                foreach (int w in tableLayoutPanel1.GetColumnWidths())
                {
                    Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);
                    //surface.DrawRectangle(p, rectangle);
                    if (rectangle.Contains(e.Location))
                    {
                        surface.DrawRectangle(p, rectangle);
                        SolidBrush myBrush=new SolidBrush(Color.Pink);
                        surface.FillRectangle(myBrush, rectangle);
                        tableLayoutPanel1.SendToBack();
                        MessageBox.Show(String.Format("row {0}, column {1} was clicked", row, column));

                        return;
                    }
                    horizontalOffset += w;
                    column++;
                }
                verticalOffset += h;

                row++;
            }

        }
Posted
Updated 14-Nov-10 21:12pm
v2

Rectangle isn't a drawing control. It's just a class that holds a TopLeft point, a width and height, describing the dimensions of a Rectangle. It doesn't draw anything.

You also should NOT be calling this.CreateGraphics. All painting should be done in the Paint event for the control you're painting on.
   
I wouldn't try to draw in the TLP itself. I'd drop a Panel control in the cell you want to draw, set it to Fill and draw on that.

Actually, I'd probably create my own drawing control that does what I need, inherited from Panel and drop that in a cell in the TLP.
   
Comments
Htike Htike Aung 15-Nov-10 22:11pm
   
Thanks.At first,we use panel.We are trying to use rectangle in tablelayoutpanel because we think using rectangle is lighter than the panel.That's why we want to change the design.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900