Click here to Skip to main content
16,020,257 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Asp.net controls are not accessible in code behind
<asp:TextBox id="txtname" class="form-control"  runat="server"></asp:TextBox>
Posted
Updated 23-Aug-19 9:59am
v2

1 solution

check out this example and see if you have something missing:

index.aspx
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="ProjectName.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <%--<input runat="server" type="text" id="txtName" />--%>
            <asp:TextBox runat="server" ID="txtusername" />
            <button type="submit">submit</button>
        </div>
    </form>
</body>
</html>


and the server code in index.aspx.cs:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ProjectName
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterError(txtName.Value.Trim());
            RegisterError(txtusername.Text.Trim());
        }

        private void RegisterError(string MsgError)
        {
            if (MsgError.Length > 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowErrorMessage", "alert('" + MsgError.Replace("'", "").Replace("\r\n", "") + "');", true);
            }
        }
    }
}
 
Share this answer
 
Comments
Richard Deeming 3-Jun-15 12:45pm    
Those .Replace calls should be replaced with HttpUtility.JavaScriptStringEncode if you want to avoid XSS.
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowErrorMessage", "alert(" + HttpUtility.JavaScriptStringEncode(MsgError, true) + ");", true);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900