【问题标题】:Instantiated null variable, null reference error and on constructor in new form实例化空变量、空引用错误和新形式的构造函数
【发布时间】:2014-03-07 02:52:57
【问题描述】:

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

    "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 即使它是从同一 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"));
    }
}

}

【问题讨论】:

  • 你能告诉我你用来绑定listHoursLog的代码吗?我认为listHoursLog.SelectedItem 不能直接转换为ManualTime,因此它返回null

标签: c# winforms casting listboxitem


【解决方案1】:

我认为这行是错误的:

ManualTime editRecord =  listHoursLog.SelectedItem as ManualTime;

您需要将所选项目转换为 ManualTime,而不是cast。强制转换将始终返回 null,因此会出现错误。

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

【讨论】:

  • 看起来属性应该能够使用该项目。我有另一个教练给我的小部件示例,小部件行简单地返回它们。我没有看到特殊的解析方法。但你可能是对的,我可能需要这样做。
  • 想通了。与您所说的类似的问题,我有一个自定义方法可以在其他地方添加列表项。它还强制转换为列表中的每个项目的字符串,这是一个问题,需要将其转换为字符串()。写入记录的对象说在我将其添加到列表框时将其变为字符串。它只需要是对象类型,而不是 tostring,因此它无法区分,ToString 覆盖需要是隐式的,因此它保留 ManualTime 对象。我修复了这两种方法,现在可以使用了。铸造并不总是正确的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多