How to access span id in code behind

34,903

You can use a Label instead of a html-span (which is also rendered as span) or you could add runat="server". Setting runat="server" allows you to access the HTML element in the code behind just as any other server control, via its ID.

<span id="expTrainingShow" runat="server" class="clsLink" style="margin-left: 20px;" onclick="GridChanger();" ></span>

somewhere in codebehind(the span is a HtmlGenericControl on serverside):

expTrainingShow.InnerHtml = yourText ' set the text '

or

expTrainingShow.Visible = False ' hide it '

Note that Visible=False on serverside means that the control is not rendered at all on clientside, hence it does not exist in the html and can be accessed only on serverside.

If you just want to hide it but render it anyway, you should use CSS or expTrainingShow.Style.Add("display","none").

Share:
34,903
NealR
Author by

NealR

Updated on July 05, 2022

Comments

  • NealR
    NealR almost 2 years

    I have an asp website with the following control:

        <span id="expTrainingShow" class="clsLink" style="margin-left: 20px;" onclick="GridChanger();">
            + Show Expired Continuing Education</span>
    

    I want to hide this based on a condition set in the code behind. Can I access a span id like that? (the website is built using visual basic)

  • NealR
    NealR over 11 years
    We need the onlick function to run client side. Will adding runat="server" interfere with the method or just the span id display?
  • Tim Schmelter
    Tim Schmelter over 11 years
    You can use runat=server and use it as any other html control. But note that it won't be rendered at all on clientside if you set Visible=False (see my edit). I you just want to hide but render it, you should use css or expTrainingShow.Style.Add("display","none").
  • NealR
    NealR over 11 years
    I just need it to work when it is visible. You are saying that as long as it is visible the onclick method (some simple clientside javascript at the top of the page) will be executed client side?
  • Tim Schmelter
    Tim Schmelter over 11 years
    You can use it as any other html control, so on clientside the runat=server does not exist and javascript works also.
  • Sergiu
    Sergiu over 8 years
    What is the corresponding .net control for HTML label and span from the System.Web.UI.HtmlControls namespace? I couldn't find any in the class collection - there are for inputs with all their associated types (text, button, radiobuttons, etc) but nothing for spans and labels. Any clue? Well what I need in fact is to be able to get the corresponding control type programatically (eg. Control c; if (c is HtmlLabel) {c.innerText = "something"} ;
  • Tim Schmelter
    Tim Schmelter over 8 years
    @Sergiu: span and label are HtmlGenericControl at serverside if you make them runat=server.