0

I am a nooby trying to learn mvc in C# winforms, but I cant seem to understand why my instance turns null on me.

View Form

 public partial class Form1 : Form, ISingleTagProperties
{
   .....        
    PropController _propController;

    public void SetController(PropController controller)
    {      
        _propController = controller;
    }
.....
   private void dataGridView3_CurrentCellChanged(object sender, EventArgs e)
   {
       _propController.updateProperites(dgv);
   }

Edit:Calling updateProperties is what gives me the null reference.

Controller PropController class

public class PropController
{
     SingleTagProperties _view;

    //constructor
    public PropController(SingleTagProperties view)
    {
        _view = view;
        view.SetController(this);
    }
......

View Instance ISingleTagProperties

 public interface ISingleTagProperties
{
    void SetController(PropController controller);

    string TagName { get; set; }
    string TagDescription { get; set; }
.....

SetController fires and _propController comes out not null, but then further down in the form trying to call a method from the PropController class gives a NullReferenceException saying that _propController is null.

There's probably some basic understanding I am missing somewhere, but I can't seem to figure it out.

MDeadman
  • 3
  • 2

2 Answers2

1

The sequence of events must be:

  1. The form is created.
  2. ...
  3. You create the view, passing in the form as a constructor parameter, which sets _propController.

When you create the form, all the other controls likely get created too (usually by a call made in the constructor to a method in the partial class generated for you by the tooling).

This is effectively step 3 above, and I suspect the process of initialising those controls is triggering that event. Because that happens before step 2, _propController is not set.

You might want to put in a null check or other work-around, although having a reference to the controller from the view seems to break the very MVC separation you wanted to achieve.

Gary McGill
  • 26,400
  • 25
  • 118
  • 202
  • Ohh that makes sense adding a null check seems to have solved the problem. I understand how I was structuring events wrong. Thanks for the answer! – MDeadman May 15 '15 at 17:40
0

You're using the wrong tools for the job...

If you want to learn MVC, use ASP.NET MVC (Model View Controller), if you want to learn a design pattern that's suited for desktop / mobile application development, get started with WPF and learn MVVM (Model View ViewModel).

Here's an excellent resource which you can learn from:

PluralSight: ASP.NET MVC 5 - Fundamentals

Aydin
  • 15,016
  • 4
  • 32
  • 42
  • I think mvvm is definitely better suited for what I am trying to do. Thanks for the help – MDeadman May 15 '15 at 17:25
  • Your welcome, if you've found that this has answered your question, please choose it as the selected answer. Cheers – Aydin May 15 '15 at 17:29