简体   繁体   中英

How to access span class in codebehind?

Is it possible display/hide spans in the codebehind based on their class? I've been able to do this with a span's id but not with classes.

markup:

<span runat='server' id='myId' class='myClass'>some text</span>

codebehind:

protected override void OnPreRender(EventArgs e)
{
    // This works
    myId.Visible = false;

    // This doesn't work
    myClass.Visible = false;
}

I get the error "The name myClass does not exist in current context". But the codebehind has no trouble with the id.

No, there is nothing that exists that lets you refer to something by class; only the ID actually works in the code-behind. You can find the object by ID, and then check it's class, or you can define a container control around something:

<asp:Panel ID="X" runat="server">
.
.
</asp:Panel>

And using this, you can loop through the controls in the panel, check the class, and process it, like:

foreach (var c in X.Controls)
{
   if (c is WebControl && ((WebControl)c).CssClass == "myClass")
      //Do something
   else if (c is HtmlControl && ((HtmlControl)c).Attributes.ContainsKey("class") && ((HtmlControl)c).Attributes["class"] == "myClass")
      //Do something

}

That's possible to do. You could also do it at the page level, but would have to do it recursively, and it may affect your apps performance.

You could try something like this:

<span runat='server' id='myId' class='myClass'>some text</span>
    ...
</span>


myId.Attributes.Add("style", "display:none;");

Of course it will not. You are using class name as an Id.

You can select the control using Contols Collection on Page object.

foreach (Control c in Page.Controls)
    {
            if (c.CssClass == "myClass")
            {
                c.Visible=false;
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM