Kameron
Kameron

Reputation: 733

ASP.NET refer a control from .aspx file

I have the following code :

<html xmlns="http://www.w3.org/1999/xhtml">

<body style="height: 1336px">
<input type="hidden" id="loadingtime"/>
.
.
.
.
</body>
</html>

and the Code.cs file is :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string s = "";
        HiddenField t = (HiddenField)Page.FindControl("loadingtime");
        s = t.Value;
        Response.Write("<script language='javascript'>alert('It took : " + s + "')</script>");
    }
}

I get error Any idea?

EDIT : The above problem is successfully solved by Now when I retrieve the value of loading time, the value is empty string. Can anyone please solve this one? enter image description here

Upvotes: 0

Views: 375

Answers (1)

Royi Namir
Royi Namir

Reputation: 148514

Your input should have runat="server" enabling it to be parsed by the ASP.NET runtime i.e.

<input type="hidden" runat="server" id="loadingtime"/>

You can then refer to the control as you would normally in code behind using:

HiddenField t = (HiddenField)loadingtime;

AS LONG AS it is not wrapped in another server control such as an asp:repeater in which case you would need to use alternative method of traversing the control hierarchy

Upvotes: 4

Related Questions