实例化的null变量,null引用错误和新形式的构造函数

时间:2014-03-07 02:52:57

标签: c# winforms casting listboxitem

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

    "An unhandled exception of type 'System.NullReferenceException' occurred in HHONamespace.exe"

Additional information: Object reference not set to an instance of an object."

问题很简单,在将editRecord变量强制转换为ManualTime之前,当它应该具有列表框中的选定记录值时,我得到一个null。我测试了调试器并且它读取了null,即使它是从同一个ManualTime类的覆盖构造的列表记录,也是从listBox强制转换的。这很难解释,可能会发生什么?为什么断开连接将属性写入随后使用此变量的编辑器表单?编辑器表单中的构造函数失败,因为此变量实例是空引用。代码一直有效,直到数据结构的最终转换是奇怪的。

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.");
            }
        }
    }
}

... ManualHours编辑器表单使用此构造函数...

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

这是ManualTime类......很简单。

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

}

1 个答案:

答案 0 :(得分:0)

我认为这一行是错误的:

ManualTime editRecord =  listHoursLog.SelectedItem as ManualTime;

您需要所选项目转换为ManualTime,而非强制转换。强制转换将始终返回null,因此错误。

如果所选项是一个字符串,那么您可以在ManualTime类中编写一个Parse()函数来转换字符串,类似于ToString()函数的反转。