实例化的空变量,无效参考误差以及新形式的构造函数



我当前在代码块上遇到此错误。请评论或提供建议如何解决此问题。谢谢。

    "An unhandled exception of type 'System.NullReferenceException' occurred in HHONamespace.exe"
Additional information: Object reference not set to an instance of an object."

问题很简单,在将editRecord变量铸造为手动时间之前,我将在其中的列表框中获得选定的记录值时,我会得到一个空。我测试了调试器,即使它是从同一手动时间类构成的列表记录,也读取了NULL,即这很难解释,可能会发生什么?为什么断开将属性写入此变量随后的编辑器表单的连接?由于此变量实例,编辑器形式中的构造函数失败是null引用。该代码工作直到最终施放数据结构,这很奇怪。

private void editBtn_Click(object sender, EventArgs e)
        {
            //NEEDS SOME DEBUGGING
            //Choose a record and select in listbox
            if (listHoursLog.SelectedIndex >= 0)
            {
                var selection = listHoursLog.SelectedItem.ToString();
                    //Identify manually entered records from timer records that begin with "M"
               if (listHoursLog.SelectedIndex >= 0 && selection.StartsWith("M"))
                {
                  ManualTime editRecord =  listHoursLog.SelectedItem as ManualTime;
                    //Launch editor
                   ManualHours newForm = new ManualHours(editRecord);
                    newForm.ShowDialog();
                    if (newForm.ShowDialog() == DialogResult.OK)
                    {
                        if (editRecord != null)
                        {
                            listHoursLog.Items.Add(editRecord);
                        }
                    }
                }
                else
                    MessageBox.Show("You may edit only the manually entered records.");
            }
        }
    }
}

...手动Hourhours编辑器表单使用此构造函数...

namespace LOG
{
    public partial class ManualHours : Form
    {
         public ManualHours()
        {
            InitializeComponent();
        }
        public ManualHours(ManualTime recordE)
        {
            InitializeComponent();
            //construct the prior data
            startDateTimePicker.Value = recordE.date;
            /*Need to parse the hours and mins to decimal*/
            hrsUpDown.Value = Convert.ToDecimal(recordE.hours.TotalHours);
            minsUpDown.Value = Convert.ToDecimal(recordE.mins.TotalMinutes);
        }

这是手动时间类...很简单。

namespace LOG
{
    public class ManualTime
    {
        public DateTime date { get; set; }
        public TimeSpan hours { get; set; }
        public TimeSpan mins { get; set; }
        public TimeSpan totalTime { get; set; }
    public ManualTime()
    {
        date = DateTime.Now;
    }
    public override string ToString()
    {
        //For list of log records
        return string.Format("Manual entry; Date: {0}, ({1} hours  + {2} mins) = Total Time: {3}",
            this.date.ToShortDateString(),
            this.hours, this.mins,
            totalTime.ToString(@"hh:mm:ss"));
    }
}

}

我认为这行是错误的:

ManualTime editRecord =  listHoursLog.SelectedItem as ManualTime;

您需要转换选定的项目为手动时间,而不是 cast it。演员将始终返回null,因此错误。

如果所选项目是字符串,则可以在手动时间类中编写一个parse()函数来转换字符串,类似于toString()functions的反面。

最新更新