Search code examples
c#windowsformslinedraw

C# windows form, Line wont Draw! canvas is not defined


What is needed to define 'canvas' on line 27? I've looked everywhere but it only gives respoenses of why an object might not be defined, and not about why the specific object canvas is not defined. Can someone tell me what i'm Missing?


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void canvas_Paint(object sender, PaintEventArgs e)
        {
            Graphics gObject = canvas.CreateGraphics();

            Brush red = new SolidBrush(Color.Red);
            Pen redPen = new Pen(red, 8);

            gObject.DrawLine(redPen, 10, 10, 35, 500);
        }
    }
}


Solution

  • That canvas must be a control in the form. You got to add it in the designer and give it the canvas name. What kind? Hmm… I'd say use a PictureBox.

    You would also need to link the Paint event to canvas_Paint from the properties panel (events tab). And yes, e.Graphics is preferred over using CreateGraphics.

    Where did you get that code from?