0

How is it possible to reference an element that is added to the html during pageload?

In my example I am trying to click a butten with the id of Clicker during page load.

However, because it is added to the html during page load, i get context error.

Error: Compiler Error Message: CS0103: The name 'clicker' does not exist in the current context


protected void Page_Load(object sender, EventArgs e)
{
//add button to html
locationsTable.InnerHtml = htmlString;

//click the button
clicker.PerformClick();
}

 htmlString += "<td><button id=\"clicker\" runat=\"server\" class=\"btn btn-default btn-xs\" onclick=\"return false;\"><span class=\"glyphicon glyphicon-option-horizontal\"></span></button>" + " " + "<a href=\"ModifyOrder.aspx?cid=" + row["CustomerID"] + "\" class=\"btn btn-primary btn-xs\">Add License</a></td>";

This htmlString is added to an html table (along with other elements, but they are irrelevant) during page load.

locationsTable.InnerHtml = htmlString;
Ophiucus
  • 95
  • 4
  • 17
  • I think you're confusing javascript with c# – Svek Feb 15 '17 at 16:52
  • nope ............................... – Ophiucus Feb 15 '17 at 16:52
  • Let's clarify then. Are you trying to perform an action when the user clicks the button with the id="clicker" that is found in html of the page? – Svek Feb 15 '17 at 16:55
  • yes. The action can be anything. I just trying to target the element with the ID of clicker. The problem is that clicker hasnt been added to the DOM yet. So the C# compiler cannot find it. So I get reference error. – Ophiucus Feb 15 '17 at 16:56
  • According to the C# compiler "clicker" doesn't exist. Because it doesnt get added to the html, or the .aspx page, until after page load. So how can I assign anything to the button clicker? – Ophiucus Feb 15 '17 at 16:57

1 Answers1

0

onclick=\"return false;\"

You cannot put c# code inside HTML like that, as it will literally turn into HTML code (it's a string, not code).

However, if you want to know have an event listener for the OnClick event hooked up to an id, I believe that this code snippet from here, can do the trick...

protected void Page_Load(object sender, EventArgs e)
{    
    locationsTable.InnerHtml = htmlString;
    htmlString += "<td><button id=\"clicker\">Add License</a></td>";

    if(IsPostBack){
        var eventTarget = Request.Params["__EVENTTARGET"]
        var buttonClicked = eventTarget.Substring(eventTarget.LastIndexOf("$") + 1).Equals("clicker")
    }
}
Community
  • 1
  • 1
Svek
  • 12,350
  • 6
  • 38
  • 69