Search This Blog

Sunday 25 August 2019

How to fire the textchanged event programmatically in ASP.net


Step 1: - Design Page

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

<!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 ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

            <asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

Step 2: - Code behind Page

using System;
using System.Text.RegularExpressions;
using System.Web.UI;

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

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TextBox1.Text))
            {
                if (Regex.IsMatch(TextBox1.Text, "[a-zA-Z]+$"))
                {
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('You entered the " + TextBox1.Text + ".')", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('Please enter only alphabet to search.')", true);
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TextBox1.Text))
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('Please enter text to search.')", true);
                return;
            }

            TextBox1_TextChanged(null, EventArgs.Empty);
        }
    }
}