如何检查某个类型的控件

本文关键字:类型 控件 何检查 检查 | 更新日期: 2024-09-19 23:38:31

当我使用下面的代码时,它是有效的。所有控件都被隐藏。

foreach (Control ctr in eItem.Controls)
{
    ctr.visible = false;                  
}

但是,我只想隐藏标签和下拉列表。这就是为什么我尝试使用以下代码但没有成功

foreach (Control ctr in eItem.Controls)
{
    if(ctr is Label | ctr is DropDownList)
    {
       ctr.visible = false;
    }              
}

编辑

以下是的整个方法

 private void HideLabelAndDDLOnPageLoad()
    {
        foreach (ListViewItem eItem in lsvTSEntry.Items)
        {
            foreach (Control ctr in eItem.Controls)
            {
                if (ctr is Label || ctr is DropDownList)
                {
                    ctr.Visible = false;
                }  
            }
        }
    }

当我删除if时,所有控件都会被隐藏。当我把它放回去时,什么也没发生。

感谢您帮助

如何检查某个类型的控件

我想你想要的是||将其更改为||。。。即逻辑或运算符。

foreach (Control ctr in eItem.Controls)
{
    if(ctr is Label || ctr is DropDownList)
    {
       ctr.Visible = false;
    }              
}

|=按位运算符

||=逻辑或操作员

基于您的编辑

如果您希望循环更新面板的内容模板容器中的所有控件,则控件似乎位于updatepanel中。

给你:

foreach (Control ctr in UpdatePanel1.ContentTemplateContainer.Controls)
 {
  // rest of code
   if(ctr is Label || ctr is DropDownList)
     {
        ctr.Visible = false;
     }         
 }  

|是按位或运算符。您正在查找逻辑或运算符||。

 if(ctr is Label || ctr is DropDownList)

如果没有确切的标记,我们只能在这里猜测解决方案。

您必须使用另一个容器将控件包装在ListView中的ItemTemplate中,类似于Panel或其他容器。当您在列表视图项上获得控件时,您实际上得到的是扭曲容器,而不是它的子对象(标签、下拉列表等)对此的一个解决方案是:

foreach (ListViewItem item in lsvTSEntry.Items)
{
    item.FindControl("myLabel").Visible = false;
    item.FindControl("myDropdownList").Visible = false;
}

基本上,你试图通过id找到控件并隐藏它们。请注意,这里没有错误检查,因此如果FindControl返回null,则可以获得NullReferenceException。

如果你在ItemTemplate中有嵌套的容器,并且你想隐藏所有的标签和下拉列表,无论它们在哪里,你可以实现你自己的递归FindControl,看起来像:

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;
}

不是最优雅的,但。。。。当然,为了提高速度,您可以将其更改为采用Id数组。当然,基于此,您可以实现按控件类型的搜索,而不是将controlId作为参数,而是将控件类型作为查找对象。