Just starting to work with shapes in C #. Here is a small program that draws a line, and when you press a button, you should draw an oval. But for some reason does not draw.

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 Блок_схема { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button6_Click(object sender, EventArgs e) { g.DrawEllipse(new Pen(Color.Black, 5), 100, 100, 20, 50); } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.DrawLine(new Pen(Color.Black, 1),new Point(200, 200),new Point(200, 300)); } } } 
  • Try to bring Graphics g to Graphics g global variables; public Form1 () {... if it does not help, I will write a more reliable way. - Specter
  • NullReferensException is such an error. If you can, then another way. - Svyatoslav
  • I thought so = ( - Specter

1 answer 1

not the most successful, poorly expandable, but working version:

 public partial class Form1 : Form { bool flag; public Form1() { InitializeComponent(); } private void button6_Click(object sender, EventArgs e) { flag = true; Refresh(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.DrawLine(new Pen(Color.Black, 1),new Point(200, 200),new Point(200, 300)); if(flag) g.DrawEllipse(new Pen(Color.Black, 5), 100, 100, 20, 50); } } 

Refresh () triggers the OnPaint () event, which recross the entire form, in your place I would encapsulate all the figures that can be drawn into a separate class, and already in OnPaint`e would draw an object of this class depending on their presence, t. e. You must have a class that describes the flowchart and the logic of working with it - get / add / delete / update flowchart elements, etc. etc, and any changes to the object would be followed by a Refresh.

  • Thanks, I will work. - Svyatoslav