Winforms Null Reference Exception未处理

时间:2013-09-19 17:51:02

标签: c# winforms unhandled-exception

对不起,伙计们,我知道这将是非常基本但我无法达到它。请帮忙,非常感谢

Winforms Null引用异常未处理 - 对象引用未设置为对象的实例。

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

现在是EditClient(表单类):

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;
   }
}

你能告诉我这是什么原因吗?我尝试了几种方法但发生了同样的错误。

2 个答案:

答案 0 :(得分:2)

您应在致电fillForm()后致电InitializeComponent()方法

您正在获取Null引用异常,因为您的文本框为空 - 文本框(和其他控件)在InitializeComponent()方法中初始化。只有在您可以为它们分配值之后。

答案 1 :(得分:2)

您的问题是您在初始化之前尝试填写表单,因此所有文本框都为空,请在EditClient构造函数中尝试填写:

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