3

I have the following custom Control:

public class Line : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        using (var p = new Pen(Color.Black, 3))
        {
            var point1 = new Point(234, 118);
            var point2 = new Point(293, 228);
            e.Graphics.DrawLine(p, point1, point2);
        }
    }
}

And a Form where I add as new control a new instance of the Line class:

Controls.Add(new Line());

The problem is that the method OnPaint isn't called and no line is drawn. Why? How can i fix it?

Nick
  • 10,309
  • 21
  • 97
  • 201

1 Answers1

3

Your are not giving it a Size, try creating a Constructor and setting a default size there, you also seem to be using the parent controls coordinates, I would use the location of the Usercontrol to set your start position and only be concerned with the Width and Height of the control needed to contain your line.

public  Line()
{
     Size = new Size(500, 500);
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
  • 1
    Well it works, but I have a strange problem... I can draw a single line: if I add another control it isn't draw... I just added another `Controls.Add(new Line());` instruction (following the first). Do you know why? – Nick Mar 08 '14 at 19:27
  • probably being placed at the same location, What you are doing is creating a control that has a square region and depending on the coordinates of your second control it is probably be covered up. – Mark Hall Mar 08 '14 at 20:24
  • Ok, but suppose I have to draw two lines in order to display the character `X`, both my controls have the same `Size` (for example 50x50) and the same position (only the two lines have different coordinates). How can I display the second line without cover the other? – Nick Mar 09 '14 at 12:20
  • 1
    That is one of the downfalls of using winforms, you do not have true transparency. You would be better off drawing your x on the same control, doing your drawing on the container or installing the [visual basic powerpack](http://www.microsoft.com/en-us/download/details.aspx?id=25169) and using the LineShape – Mark Hall Mar 09 '14 at 13:00