Reputation: 1285
I am adding one panel to another panel it works but circle which is in inspanel not shown. how can i solved this. I am using below code. It works but not show circle
public static int xTemp = 0;
public static int yTemp = 0;
private void button1_Click(object sender, EventArgs e)
{
Panel insPanel = new Panel();
Random xRandom = new Random();
xTemp= xRandom.Next(20,100);
Random yRandom = new Random();
yTemp = yRandom.Next(20, 100);
insPanel.Location = new Point(xTemp, yTemp);
insPanel.Width=40;
insPanel.Height = 40;
insPanel.Visible = true;
insPanel.BorderStyle = BorderStyle.FixedSingle;
insPanel.Paint += new PaintEventHandler(insPanel_Paint);
panel1.Controls.Add(insPanel);
}
void insPanel_Paint(object sender, PaintEventArgs e)
{
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics =this.CreateGraphics();
formGraphics.FillEllipse(myBrush, new Rectangle(xTemp,yTemp, 10, 10));
myBrush.Dispose();
formGraphics.Dispose();
}
Upvotes: 0
Views: 50
Reputation: 26876
Main issue: you're trying to draw your circle at wrong coordinates.
xTemp
and yTemp
are coordinates of insPanel
relative to panel1
. But when you drawing your circle, you should use coordinates relative to panel you're drawing at - insPanel
.
Another issue: there is no need to create and dispose graphics each time you're drawing something on your panel. You can use e.Graphics
from Paint
eventhandler arguments.
Based on above, your code could look like:
void insPanel_Paint(object sender, PaintEventArgs e)
{
using (var myBrush = new SolidBrush(Color.Red))
{
e.Graphics.FillEllipse(myBrush, new Rectangle(0, 0, 10, 10));
}
}
Also note - since paint event can occur very frequently, it could be a good idea not to create and dispose brush every time, but use brush cached in your class private field.
Upvotes: 1
Reputation: 12449
Use e.Graphics
instead of this.CreateGraphics
:
System.Drawing.Graphics formGraphics = e.Graphics;
One more issue is you're getting coordinates in range of 20 - 100
(xRandom.Next(20,100)
) and your panel dimensions are just 40, 40
.
Upvotes: 0