对象引用未设置为对象日期/时间的实例
本文关键字:时间 实例 日期 对象 设置 对象引用 | 更新日期: 2023-09-27 18:30:26
为什么我总是收到此错误?"对象引用未设置为对象的实例。"
这是代码,错误指向哪里:
namespace Sell_System
{
public partial class Form4 : Form
{
private TextBox dateContainer;
private TextBox timeContainer;
private Timer timer;
public Form4()
{
InitializeComponent();
dateContainer.Text = DateTime.Now.ToString("dddd, MMMM dd, yyyy", System.Globalization.CultureInfo.InvariantCulture);
timeContainer.Text = DateTime.Now.ToString("h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
timer.Tick += new System.EventHandler(this.StartTimer);
timer.Interval = 60000;
timer.Start();
}
我之所以将其放入公共 Form4() 中,是因为我希望时间始终每 60 秒更新一次,当时间达到 00:00AM 时,日期将增加一天。
错误指向dateContainer.Text,当我注释该命令时,错误将指向timeContainer.Text等,直到计时器。开始();
在 winform 应用程序上声明和初始化控件的工作是在将控件放在窗体图面上时完成的。这样,WinForm 设计器将适当的代码添加到初始化组件,您可以在代码中使用控件。
如果像以前那样手动添加控件,则负责初始化,定义其一些基本属性并将这些控件添加到窗体控件集合中。
像这样的东西
namespace Sell_System
{
public partial class Form4 : Form
{
// Declaration of your controls....
private TextBox dateContainer;
private TextBox timeContainer;
private Timer timer;
public Form4()
{
// This is were the controls defined by the form designer will be initialized
// using all the default values for their property
InitializeComponent();
// Now you do it manually for the controls added manually
dateContainer = new TextBox();
// At least define the position where the control should appear on the form surface
dateContainer.Location = new Point(10, 10);
dateContainer.Text = DateTime.Now.ToString("dddd, MMMM dd, yyyy", System.Globalization.CultureInfo.InvariantCulture);
timeContainer = new TextBox();
timeContainer.Location = new Point(30, 10);
timeContainer.Text = DateTime.Now.ToString("h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
// To be shown the controls should be added to the Form controls collection
this.Controls.Add(dateContainer);
this.Controls.Add(nameContainer);
// The WinForm timer is just a component so it is enough to Initialize it
timer = new System.Windows.Forms.Timer();
timer.Tick += new System.EventHandler(this.StartTimer);
timer.Interval = 60000;
timer.Start();
}
}
如果必须定义控件的许多属性,则以这种方式创建控件可能会很快变得混乱。因此,如果动态需求并不真正需要,则手动创建控件并不是一个好的做法。
当你创建一个类实例时,比如
private TextBox dateContainer;
它将为 null,直到程序的某些部分为其分配值。您需要在讲师或 init 函数中编写dateContainer = ...
。