aspx element is not recognized in code behind (asp.net)

I created an element with runat=”server” tag but i cannot be recognized in the code behind.(“time” is not recognized)

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="game.aspx.cs" Inherits="RapidTyper.game" %>

<!DOCTYPE html>
        <div runat="server">
    <a runat="server" id="time"></a>
        </div>
    <asp:Button ID="UpdateResults" runat="server"  ClientIDMode="Static" style="display:none;" OnClick="Button1_Click" Text="" />

code behind

 protected void Button1_Click(object sender, EventArgs e)
    {
        int score = time.Text;

    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

the element <a runat="server" id="time"></a> is not an asp.net element but an Html element that have no Text property.

You can use the LinkButton <asp:LinkButton runat="server" ID="time2"></asp:LinkButton> that renders <a> Tag and have Text property.

  • also the <a> Tag is not an input element and is not post back anything – so the score = time.Text is not going to get anything other than the one you have all ready set previously.

Method 2

What Aristos has written is correct, but your problems go deeper than this. In order to use elements like <asp:Button /> you need to place them within a form which in turn needs to be within a <body> . At the very least you need something like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="eShop.test" %>


<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox runat="server" id="time" />
        </div>
    <asp:Button ID="UpdateResults" runat="server" OnClick="UpdateResults_Click" />
        </form>
</body>
</html>

Note That I have assumed that you also need something like an <asp:TextBox>. I presume this should be some sort of a user input? Finally you will not be able to simply do int score = time.Text since Text is a string. At the very least you need int score = int.Parse(time.Text) but this will only work, if the box contains an actual integer. Anything else will throw an error. Instead you should look at int.TryParse


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x