Reputation: 1003
I need to draw a rectangle around the edge of a panel created dynamically during runtime. First of all, I get a color in hexa code. I am converting it into ARGB using a code I found here on stackoverflow in similiar question:
string color = *getting the hexa code*
int argb = Int32.Parse(color.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
Now, I try to draw the rectangle using this code:
Graphics g = panel.CreateGraphics();
Pen p = new Pen(clr);
Rectangle r = new Rectangle(1, 1, 578, 38);
g.DrawRectangle(p, r);
But it does nothing, no rectangle appears.
This code is included in a part of code that creates the panel itself and populates it with some controls (Comboboxes, buttons etc.). Do I need to add the rectangle to the panel using something like panel.Controls.Add(r);
? (Tried that, of course rectangle is not a control so it doesnt work)
Upvotes: 0
Views: 844
Reputation: 43636
Try shifting the Graphics drawing into the panels paint event, since you are creating these dynamicly an anonymous event handler should make it easy.
private void CreatePanel()
{
Panel panel = new Panel();
panel.Width = 600;
panel.Height = 100;
panel.Controls.Add(....);
panel.Paint += (sender, e) =>
{
string color = "#FFE80000"; //*getting the hexa code*
int argb = Int32.Parse(color.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
Pen p = new Pen(clr);
Rectangle r = new Rectangle(1, 1, 578, 38);
e.Graphics.DrawRectangle(p, r);
};
Controls.Add(panel);
}
Upvotes: 1