[英]Error System.NullReferenceException
嗨,大家好,當我嘗試執行項目時,當我嘗試存儲對象時就會出現此錯誤。 如您所見,這是取貨表格,允許用戶將值存儲在不同的類中。 值將存儲在3個不同的類中。.您會發現c#仍然是新手。 我有客戶類別,該類別將存儲客戶的詳細信息,取件類別以及取件的詳細信息,以及交貨信息。 與其他類一起使用,Visitor將僅在發生時間時存儲。 我不知道這是否是問題..讓我知道您是否想查看更多代碼..謝謝
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace coursework2
{
public partial class PickupForm : Form
{
private MainForm mainform;
private Pickup thePickup;
private Delivery theDelivery;
private Visit theVisit;
public Pickup pickup
{
get { return thePickup;}
set { thePickup = value;}
}
public Delivery delivery
{
get { return theDelivery; }
set { theDelivery = value; }
}
public Visit visit
{
get { return theVisit; }
set { theVisit = value; }
}
public PickupForm()
{
InitializeComponent();
}
/*public MainForm ParentForm
{
get { return mainform; }
set { mainform = value; }
}*/
private void PickupForm_Load(object sender, EventArgs e)
{
if (thePickup != null)
{
textCname.Text = thePickup.PickupName;
textAddress.Text = thePickup.PickupAddress;
textDate.Text = theVisit.DateTime.ToString();
textDname.Text = theDelivery.DeliveryName;
textDaddress.Text = theDelivery.DeliveryAddress;
}
}
private void btnReturn_Click(object sender, EventArgs e)
{
this.Close();
/*mainform.Show();*/
}
private void btnClear_Click(object sender, EventArgs e)
{
textCname.Clear();
textAddress.Clear();
textDate.Clear();
textDname.Clear();
textDaddress.Clear();
}
private void btnPickup_Click(object sender, EventArgs e)
{
thePickup.PickupName = textCname.Text; //error occurs from this line
thePickup.PickupName = textAddress.Text;
theVisit.DateTime = DateTime.Parse(textDate.Text);
theDelivery.DeliveryName = textDname.Text;
theDelivery.DeliveryAddress = textDaddress.Text;
this.Close();
}
private void textDate_TextChanged(object sender, EventArgs e)
{
}
private void textCname_TextChanged(object sender, EventArgs e)
{
}
}
}
您正在訪問thePickup
屬性,但thePickup
沒有為該變量分配對象。 所以thePickup
仍然為null
,這就是為什么您得到NullReferenceException的原因。
在某些時候,您需要實例化一個Pickup
對象並將其分配給thePickup
如下所示:
thePickup = new Pickup();
您可能應該在構造函數或PickupForm_Load
事件處理程序中執行此操作。
theVisit
和theDelivery
。
private void PickupForm_Load(object sender, EventArgs e)
{
if(thePickup == null)
{
thePickup = new Pickup();
}
if(theDelivery == null)
{
theDelivery = new Delivery();
}
if(theVisit == null)
{
theVisit = new Visit();
}
textCname.Text = thePickup.PickupName;
textAddress.Text = thePickup.PickupAddress;
textDate.Text = theVisit.DateTime.ToString();
textDname.Text = theDelivery.DeliveryName;
textDaddress.Text = theDelivery.DeliveryAddress;
}
您需要初始化各自的屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.