我试图隐藏<li>
,但它不工作:
<li runat="server" id="theLi">This is test</li>
c#代码:
theLi.Visible = false;
错误* *
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
参考:如何:按ID访问服务器控件https://learn.microsoft.com/en-us/previous-versions/y81z8326 (v = vs.140) ? redirectedfrom = MSDN
您可能正在尝试访问命名容器内的控件。
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
一旦你调用了这个函数,你可以使用可见性状态
var ctrl = FindControlRecursive(this, "theLi");
if (ctrl !=null) {
ctrl.Visible = false;
}