如何在以管理员身份登录后启用该按钮
本文关键字:启用 按钮 登录 身份 管理员 | 更新日期: 2023-09-27 18:23:35
例如,我有一个登录表单和另一个表单。有些按钮被禁用,因为有些按钮只供管理员使用,我尝试了这个代码,然后在调试完弹出的消息Object reference not set to an instance of an object.
后对其进行调试
if (labelLogAs.Text == "Manager")
{
(this.Owner as MainMenu).buttonInventory.Enabled = true;
}
您会得到此错误,因为使用as
运算符的操作返回了null
。要避免此错误,您需要执行安全检查。您有两个选项来执行此security check
:
使用as
运算符:
if (labelLogAs.Text == "Manager")
{
var owner = this.Owner as MainMenu;
if(owner !=null)
owner.buttonInventory.Enabled = true;
}
使用is
运算符:
if (labelLogAs.Text == "Manager")
{
if(this.Owner is MainMenu)
((MainMenu)this.Owner).buttonInventory.Enabled = true;
}
他自行决定使用哪种安全检查来避免这个错误。
如果您得到错误"Object reference not set to a instance of a Object",则表示某个对象为null。请对其进行调试,以找到确切的null。在您的情况下,以下表达式之一为null,您可以通过在调试器中遍历代码并观察表达式来找到它:
labelLogAs
this.Owner as MainMenu
(this.Owner as MainMenu).buttonInventory
Ilya Kogan答案的补充。当使用as
运算符时,您应该进行null检查,如下所示:
var owner = (this.Owner as MainMenu);
if(owner == null)
return;
这只是一个例子,不一定符合您的需求。