Adding a Rectangle object to a Panel
I was able to add a button/label to a Panel like this;
this.panel1.Controls.Add(this.button1);
this.panel1.Controls.Add(this.label11);
Works..OK!
But, what I need is to add a Rectangle object to a Panel.
I draw a Rectangle object;
Graphics graph = this.CreateGraphics();
Pen penCurrent = new Pen(Color.Red);
Rectangle Rect = new Rectangle(300, 50, 150, 75);
graph.DrawRectangle(penCurrent, Rect);
But when i do like this;
this.panel1.Controls.Add(this.Rect);
it gives an ERROR!
-----
Says;
Controls.Add() , works only for System.Windows.Forms.Control and CanNOT work with System.Drawing.Rectangle
-----
So how can i achive this;
add a Rectangle object to a Panel
Jan MontanoPosted May 30, 2007, 5:11 AM
ugpPosted May 27, 2007, 2:28 AM
Richard BlythePosted May 25, 2007, 1:16 PM
(1)
Add a picturebox to the form
You can create the same rectangle.
Paint it onto a bitmap
Set the picturebox image to the painted bitmap.
//Sample code
Rectangle Rect = new Rectangle(300, 50, 150, 75);
Bitmap myBitmap = new Bitmap(Rect.Width,Rect.Height);
Graphics g = Graphics.FromImage(myBitmap);
// always dispose the graphics object if you have created it
g.Dispose();
pictureBox.Image = myBitmap;
The second option takes a little more time to implement but it is more efficient
(2)
In the Designer view, select the panel - click on the "Properties" window - Inside the window click the "Events" button (the lightning bolt) - Scroll down and find the "Paint" event - DoubleClick to generate an event handler.
This the code you would insert inside the panel's Paint event. Note: This code assumes that the rectangle object has already been created.
//Sample code Note: code will execute slightly faster if you use a predefined pen object
e.Graphics.DrawRectangle(
Pens.Red, Rect);Hope this will help you!
Richard