check out this example and see if you have something missing:
index.aspx
<%@ 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>
<%----%>
<asp:TextBox runat="server" ID="txtusername" />
<button type="submit">submit</button>
</div>
</form>
</body>
</html>
and the server code in
index.aspx.cs
:
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(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);
}
}
}
}