I create a PictureBox in the class, it is displayed, but when I try to draw something on it, I get a whole nothing. No error, no line. Left a piece of code for clarity. In the case, it enters, but the line is not drawn, like any other object.

class maker { string path; string[] file_mass; Form1 f1; Size s1; double[,] mass; Graphics gr; PictureBox p1; Pen pen = new Pen(Color.Red,1); public maker(Form1 main_form,string file_path) { path = file_path; f1 = main_form; s1 = new Size(500,600); p1 = new PictureBox(); p1.Location = new Point(0, 0); p1.Size = s1; p1.BackColor=Color.Black; f1.Controls.Add(p1); f1.Size = s1; gr = p1.CreateGraphics(); draw(); } private void draw() { _file_mass(); _mass(); correct_size_move(); for (int i = 1; i < mass.GetLength(0); i++) { switch (mass[i,0]) { case 0: gr.DrawLine(pen, 0, 0, 50, 50); break; default: break; } } } 

When loading a form, I call it like this:

 maker run = new maker(this, @"C:\Users\admin\Desktop\1.txt"); 

    1 answer 1

     //Graphics gr; ... //gr = p1.CreateGraphics(); p1.Paint += pbPaint; private void draw() { using (Graphics gr = p1.CreateGraphics()) { draw(gr); } } private void pbPaint(object sender, System.Windows.Forms.PaintEventArgs e) { draw(e.Graphics); } private void draw(Graphics gr) { _file_mass(); _mass(); correct_size_move(); for (int i = 1; i < mass.GetLength(0); i++) { switch (mass[i,0]) { case 0: gr.DrawLine(pen, 0, 0, 50, 50); break; default: break; } } } 

    Or create a picture, draw on it and assign p1.Image .


    The pbPaint method pbPaint used as a handler for the Paint event. This event occurs whenever the control needs to be redrawn.

    When we create draw() with no parameters when creating controls, we draw something on the surface of the control p1 . At the nearest redraw of the control, what we drew will disappear. Since draw() is called before the form appears on the screen, I think that we will not see it at all. And here we use the Paint event - we draw everything every time the control tells us that it redraws its surface.