Click here to Skip to main content
15,905,325 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a custom control, i want to draw a line in its client when i drag that custom control to Form.

I code it as follows:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
        private float _LineWidth = 1.0F;
        public float LineWidth
        {
            get
            {
                return _LineWidth;
            }
            set
            {
                _LineWidth = value;
                PaintLine();
                Invalidate();
            }
        }
        private void PaintLine()
        {
            Graphics surface;
            surface = this.CreateGraphics();
            Pen pen1 = new Pen(Color.Blue, _LineWidth);
            surface.DrawLine(pen1, 10, 10, 100, 100);
        }
    }
}


But it doesnt work, what is happened? Hope everyone helps me. Thanks.
Posted

There are a couple of things wrong here.

Firstly, the LineWidth setter will only be actioned when you set the LineWidth Property - which you don't seem to be doing. Settign teh value of _LineWidth will not cause the LineWidth setter to be called.

Second it is a very bad idea to do any painting outside the Paint Event - it will not get redrawn if the control is re-sized for example.

Thirdly, if you do paint outside the Paint Event, then calling Invalidate immediately afterwards is even sillier, as it will cause the Paint Event to be fired, and clear the drawing off your control...
 
Share this answer
 
Comments
Andrewpeter 3-Nov-12 6:44am    
Thanks for you answer, it's great idea to me solve my code. My vote is 5.
Sometimes I get also problems like that.
But I've solved it to do this:

First, add a Paint event handler to your control (do this in the constructor):
C#
this.Paint += UserControl1_Paint;

Then, add the UserControl1_Paint method:
C#
void UserControl1_Paint(object sender, PaintEventArgs e)
{
    Pen pen1 = new Pen(Color.Blue, _LineWidth);
    e.Graphics.DrawLine(pen1, 10, 10, 100, 100);
}

If you do that, you can remove the PaintLine method.
Also, you don't need to create a Graphics object, use e.Graphics.
If the LineWidth property is changed, change the PaintLine(); line into this:
C#
this.Refresh();

Then the method UserControl1_Paint will be invoked automatically.

Hope this helps.
 
Share this answer
 
Comments
Andrewpeter 3-Nov-12 6:43am    
Thanks, i solved! My vote is 5 for you.

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