【发布时间】: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