Sign in to follow this  
stam112

Unhandled exception in the designer

Recommended Posts

Hi, I get the following error when I Rebuild the Solution in Visual Studio: The control WindowsFormsApplication1.MyPanel has thrown an unhandled exception in the designer and has been disabled Here is what I did to get this error: 1) Started a new project and added a new User Control (MyControl) to the solution. 2) Added MyControl in the designer to the Form. 3) Added the following call to Init() method that I implemented in MyControl:
partial class Form1
{
    ....
    private void InitializeComponent()
        {
            this.myControl1 = new WindowsFormsApplication1.MyControl();
            this.SuspendLayout();
            // 
            // myControl1
            // 
            this.myControl1.Location = new System.Drawing.Point(73, 38);
            this.myControl1.Name = "myControl1";
            this.myControl1.Size = new System.Drawing.Size(150, 150);
            this.myControl1.TabIndex = 0;
            this.myControl1.Init();
            // 
            // Form1
            // 
            ....
4) Added the following code to MyControl class:
namespace WindowsFormsApplication1
{
    public partial class MyControl : UserControl
    {
        private Bitmap myImage;
        private Graphics g;

        public MyControl()
        {
            InitializeComponent();
        }

        public void Init()
        {
            myImage = new Bitmap(Width, Height);
            g = Graphics.FromImage(myImage);
            g.Clear(Color.Sienna);
            g.DrawEllipse(Pens.Red, 0, 0, 50, 50);
            g.Dispose();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.DrawImageUnscaled(myImage, 0, 0);
        }
    }
}
When I run the application, everything works fine. But when I "Rebuild Solution" I got the "unhandled exception in the designer" error. Please help to understand why this is happening. Thanks a lot !

Share this post


Link to post
Share on other sites
Good point !
I had a feeling that inserting the Init() call there isn't a good idea, but I couldn't find a better solution.
The problem is that inside OnPaint(..) method of MyControl, myImage should be already initialized according to MyControl's Width and Height.
I tried to do the initialization in Form1_Load, but it's too late (OnPaint of MyControl is called first).
Do you have a better solution ?

By the way, the "Unhandled exception in the designer" error message pointing to this line:
e.Graphics.DrawImageUnscaled(myImage, 0, 0);

saying that myImage is null.
Why is that ??

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this