C# 检查按钮属性值-BackgroundImage

C# 检查按钮属性值-BackgroundImage,c#,C#,我试图通过检查按钮的width属性来检查之前是否在按钮上设置了iamge。如果未设置,则我想设置iamge,但我 我得到以下错误。我对C#还不熟悉,所以如果它太基本,请原谅我 错误:对象引用未设置为对象的实例 if (button1.BackgroundImage.Width == 0) // Error on this line { button1.BackgroundImage = Properties.Resources.SubmitButton; // Works fine i

我试图通过检查按钮的width属性来检查之前是否在按钮上设置了iamge。如果未设置,则我想设置iamge,但我 我得到以下错误。我对C#还不熟悉,所以如果它太基本,请原谅我

错误:对象引用未设置为对象的实例

if (button1.BackgroundImage.Width == 0)  // Error on this line
{
    button1.BackgroundImage = Properties.Resources.SubmitButton; // Works fine if put out of conditon
}
else
{
    button1.BackgroundImage = null;
}

在设置提交按钮图像之前,可能需要检查null。更新后的代码如下所示:

if (button1.BackgroundImage == null || button1.BackgroundImage.Width == 0)  // Error on this line
{
    button1.BackgroundImage = Properties.Resources.SubmitButton; // Works fine if put out of conditon
}
else
{
    button1.BackgroundImage = null;
}

希望这能有所帮助。祝你好运

不需要检查宽度,检查null就足够了。@ArinGhazarian你说得对!只是尽可能地坚持原来的代码片段。谢谢。否则基本上就是打开/关闭图像。