I wrote bresenham algorithm for
0<Angular coefficient<1
I don’t know much about graphics in C#,I realized that for drawing pixles I can use the function Fillrectangel with coordinate 1,1
I wanted to write my code then when clicking the mouse on panel and in two positions draw me a line from x0,y0 to xEnd,yEnd
so here is my code which has exception

Null reference exception was unhandled
object reference not set to an instance of the object
this exception is in line e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
I think the problem is that object e is Null and I should new it but how?
How can I correct my code so as to draw Line?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Line l=new Line();
l.LineBres(Cursor.Position.X, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
}
}
}
public class Line
{
System.Windows.Forms.DrawItemEventArgs e;
Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2 * dy - dx;
int twoDy = 2 * dy;
int twoDyMinusDx = 2 * (dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}
Here is what you need to change:
Add mouse click event for panel and change your Line code a bit – remove
System.Windows.Forms.DrawItemEventArgs e;and pass Graphics of panel withpanel1.CreateGraphics();. Here is the code: