0

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

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

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

你能告诉这是什么原因造成的吗?我尝试了几种方法,但出现同样的错误。

4

2 回答 2

2

你应该在调用之后调用你的fillForm()方法。InitializeComponent()

你得到一个空引用异常,因为你的文本框是空的 - 文本框(和其他控件)在InitializeComponent()方法中被初始化。只有在您可以为它们分配值之后。

于 2013-09-19T17:57:17.097 回答
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();        
}
于 2013-09-19T17:58:09.660 回答