大家好,当我尝试执行项目时,当我试图存储对象时出现此错误。正如您所看到的,这是拾取形式,允许用户将值存储在不同的类中。这个值将有3个不同的类存储在...你看到我仍然是c#thing的新手。我有客户类,将存储客户的详细信息,皮卡类别与皮卡的详细信息和交付相同。和其他类访问只会在时间到来时存储。我不知道这是不是问题..如果你想看到更多代码,请告诉我..谢谢
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)
{
}
}
}
答案 0 :(得分:1)
您正在访问thePickup
的属性,但在任何时候都没有为变量分配对象。所以thePickup
仍然是null
,这就是你得到NullReferenceException的原因。
在某些时候,您需要实例化一个Pickup
对象并将其分配给thePickup
,如下所示:
thePickup = new Pickup();
您应该在构造函数或PickupForm_Load
事件处理程序中执行此操作。
theVisit
和theDelivery
同样如此。
答案 1 :(得分:0)
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;
}
您需要初始化各自的属性