我在MessageBox上选择是时出现问题,按钮是或否。
Object reference not set to an instance of an object.
来自行:
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
我不明白这是什么问题,因为在此之后几行,是同一个声明。我该如何解决这个问题?
固定
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
答案 0 :(得分:2)
您正在访问storedAuth
的属性,但刚刚检查到storedAuth
为空,因此此代码保证抛出NullReferenceException
。 ..
答案 1 :(得分:1)
看看这句话 if(storedAuth == null)
并且您访问null对象的属性。如果是必需的对象,则为该对象赋值,然后访问UserName和Password。
这是错误的原因..您不应在以下语句中使用storedAuth.UserName,storedAuth.Password)。使用一些默认值,如“”或“默认”
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password
);
addWindow.ShowDialog();