locked
Graphics, Drawline function raises System.NullReferenceException RRS feed

  • Question

  • Hi, i am beginner in Graphics in VC++ Windows Form Application, I would like to draw a line on button click, here is my code:

     

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    Graphics^ pencil;
    Pen^ blue = gcnew Pen(Color::Blue);
    pencil->DrawLine(blue, 100, 100, 100, 100);
    }

    The application runs. but when i press the button it raises that error:

    System.NullReferenceException

    Why does this happen? Thanks

    Monday, October 14, 2013 8:24 PM

Answers

  • Try:

    Graphics^ pencil = this->CreateGraphics();
    warning: untested



    Tuesday, October 15, 2013 7:51 PM

All replies

  • It happens because pencil is null, seeing as you haven't assigned any value to it.

    Igor Tandetnik

    • Proposed as answer by Anna Cc Tuesday, October 15, 2013 9:57 AM
    Monday, October 14, 2013 9:37 PM
  • But how am i going to assign a value to the pencil? When i try: Graphics pencil = e->Graphics the compiler raises another error, which says that Graphics is not a member of SystemEventArgs... I don't want to use PaintEventArg, because i want to do it on button click... 


    Tuesday, October 15, 2013 5:45 PM
  • Try:

    Graphics^ pencil = this->CreateGraphics();
    warning: untested



    Tuesday, October 15, 2013 7:51 PM
  • Thank you very much, it is working!
    Wednesday, October 16, 2013 5:01 PM