Question

Sorry guys, I know it'll be pretty basic but I can't get to it. Please help, Thanks a lot

Winforms Null Reference Exception was unhandled - Object reference not set to an instance of an object.

Model.ClientModel Client = new Model.ClientModel(); // Create Instance of Model
Client.id = int.Parse(row.Cells[0].Value.ToString()); // Setting fields
Client.clientName = row.Cells[1].Value.ToString();// Setting fields
Client.company = row.Cells[2].Value.ToString();
Client.website = row.Cells[3].Value.ToString();
Client.emails = row.Cells[4].Value.ToString();
Client.phone= row.Cells[5].Value.ToString();
Client.mobile = row.Cells[6].Value.ToString();
Client.location = row.Cells[7].Value.ToString();
Client.referrer = row.Cells[8].Value.ToString();
Client.currency = row.Cells[9].Value.ToString();
Client.ratePerWord = row.Cells[10].Value.ToString();
Client.notes = row.Cells[11].Value.ToString();

Clients.EditClient editClient = new Clients.EditClient(Client); // Passing Model to the constructor of EditClient Class

editClient.Show(); // Displaying form

Now the EditClient (Form Class):

public partial class EditClient : Form
{
   public Model.ClientModel Client;

   public EditClient(Model.ClientModel Client)
   {
      // TODO: Complete member initialization
      this.Client = Client; //Getting the Model Object passed by the previous class
      fillForm();
      InitializeComponent();
   }

   public void fillForm()
   {
      //Here I set all the model data to the fields

      textBox1.Text = Client.clientName;  //This is where the ERROR Occurs - NULLReferenceException was unhandled.  Object reference not set to an instance of an object.
      textBox2.Text = Client.company;
      textBox3.Text = Client.website;
      textBox4.Text = Client.emails;
      textBox5.Text = Client.phone;
      textBox6.Text = Client.mobile;
      textBox7.Text = Client.location;
      textBox8.Text = Client.referrer;
      textBox9.Text = Client.currency;
      textBox10.Text = Client.ratePerWord;
      textBox11.Text = Client.notes;
   }
}

Can you please tell what is causing this? I've tried several ways but the same error occurs.

Était-ce utile?

La solution

Your problem is that you are trying to fill your form before it is initialized, so all your textboxes are null, try this instead in your EditClient constructor:

public EditClient(Model.ClientModel Client)
{
    // TODO: Complete member initialization
    this.Client = Client; //Getting the Model Object passed by the previous class
    InitializeComponent();
    fillForm();        
}

Autres conseils

You should call your fillForm() method after calling InitializeComponent().

You are getting a Null Reference Exception because your text boxes are null - the text boxes (and other controls) are initialized in the InitializeComponent() method. Only after you can assign values to them.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top