ASP.NET - Using SetFocusOnError property in validation control


asp.net Button example: how to use ClientClick event

C# Code

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;

namespace asptutorial
{
    public partial class blankpage : System.Web.UI.Page
    {

         protected void Page_Load(object sender, EventArgs e)
        {

            Label1.Text = "Name";
            Label1.Text = "Email";

            Button1.Text = "Send";

            RequiredFieldValidator1.ForeColor = System.Drawing.Color.Red;
            RequiredFieldValidator2.ForeColor = System.Drawing.Color.Red;

            RequiredFieldValidator1.ErrorMessage = "Input Name !";
            RequiredFieldValidator2.ErrorMessage = "Input Email !";

            RequiredFieldValidator1.ControlToValidate = TextBox1.ClientID;
            RequiredFieldValidator2.ControlToValidate = TextBox2.ClientID;


            RequiredFieldValidator1.SetFocusOnError = true;
            RequiredFieldValidator2.SetFocusOnError = true;
        }
    }
}

HTML Code

<%@ Page Language="C#" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
   
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Button Control </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Name" AssociatedControlID="TextBox1"></asp:Label>  
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
        <asp:RequiredFieldValidator  
             ID="RequiredFieldValidator1"  
             runat="server"  
             ControlToValidate="TextBox1"  
             ErrorMessage="Input Name!"  
             SetFocusOnError="true"  
             >  
        </asp:RequiredFieldValidator>  
        <br />  
  
        <asp:Label ID="Label2" runat="server" Text="Email" AssociatedControlID="TextBox2"></asp:Label>  
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
        <asp:RequiredFieldValidator  
             ID="RequiredFieldValidator2"  
             runat="server"  
             ControlToValidate="TextBox2"  
             ErrorMessage="Input Email!"  
             SetFocusOnError="true"  
             >  
        </asp:RequiredFieldValidator>  
        <br />  
          
        <asp:Button ID="Button1" runat="server" Text="Send" OnClick="Button1_Click" />  
    
    </div>
    </form>
</body>
</html>
Output
Using SetFocusOnError property in validation control

Share this article on