对象引用未设置为对象日期/时间的实例

时间:2013-09-05 10:22:19

标签: c# winforms

为什么我一直收到这个错误? “ 对象引用未设置为对象的实例。

这是代码,指向的错误在哪里:

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:00 AM时,日期会增加一天。

错误指向dateContainer.Text,当我注释该命令时,错误将指向timeContainer.Text,依此类推,直到timer.Start();

2 个答案:

答案 0 :(得分:1)

当您将控件放在表单的表面上时,将在winform应用程序上声明和初始化控件的工作完成。通过这种方式,WinForm设计器将相应的代码添加到InitializeComponent,您可以在代码中使用控件。

如果您手动添加控件,那么您负责初始化,定义一些基本属性并将这些控件添加到窗体控件集合中。

像这样的东西

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

如果必须定义控件的许多属性,以这种方式创建控件可能会变得非常快。因此,如果动态需求并不真正需要,手动创建控件并不是一个好的做法。

答案 1 :(得分:0)

当您创建类似

的类实例时
private TextBox dateContainer;

在程序的某些部分为其赋值之前,它将为null。您需要在讲师或init函数中编写dateContainer = ...