How to use Button ClientClick event in asp.net

Button ClientClick event
The Button web server control displays a push button control on the Web page. The Button lets users post a page to the server. The control triggers an event in server code that asp.net developers can handle to respond to the postback. The Button can also raise an event in the client script that developers can handle before the page is posted or that can run and then cancel the submission of the page.

The following asp.net c# tutorial code demonstrates how we can trigger the Button ClientClick event. In this tutorial, we showed an alert message on the web browser using the Button ClientClick event. The developers have to set the Button OnClientClick property to use the ClientClick event.

The Button OnClientClick property gets or sets the client-side script that executes when a Button control's Click event is raised. This property value is a String which is the client-side script that executes when a Button control's Click event is raised.

The asp.net c# developers can use the OnClientClick property to specify the additional client-side script that executes when a Button control's Click event is raised. The script that developers specify for this OnClientClick property is rendered in the Button control's OnClick attribute in addition to the control's predefined client-side script.
OnClientClickExample.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button2_Click(object sender, System.EventArgs e) {
        Label1.Text = "Button2 Clicked!";
    }
</script>

<script  type="text/javascript">
    function AlertOnClientClick()
    {
        alert('OnClientClick event triggered!');
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net Button example: how to use OnClientClick event</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Purple">Using OnClientClick event</h2>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkGreen"></asp:Label>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Click Me" OnClientClick="AlertOnClientClick()" Font-Bold="true" ForeColor="Teal" />
        <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" Font-Bold="true" ForeColor="Teal" />
    </div>
    </form>
</body>
</html>

ASP.NET Web.sitemap file Example

A sample Web.sitemap file
Web.sitemap

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="Default.aspx" title="Home"  description="Home Page">
      <siteMapNode url="StandardToolBox.aspx" title="StandardToolBox" description="StandardToolBox Controls">
        <siteMapNode url="AdRotatorExample.aspx" title="AdRotator"  description="AdRotator Example" />
        <siteMapNode url="BulletedListExample.aspx" title="BulletedList"  description="BuulletedList Example" />
        <siteMapNode url="ButtonExample.aspx" title="Button"  description="Button Example" />
        <siteMapNode url="CalendarExample.aspx" title="Calendar"  description="Calendar Example" />
      </siteMapNode>
      <siteMapNode url="DataToolBox.aspx" title="DataToolBox" description="DataToolBox controls">
        <siteMapNode url="ListViewExample.aspx" title="ListView"  description="ListView Example" />
        <siteMapNode url="GridViewExample.aspx" title="GridView"  description="GridView Example" />
      </siteMapNode>
      <siteMapNode url="NavigationToolbox.aspx" title="Navigation Toolbox" description="NavigationToolbox controls">
        <siteMapNode url="MenuExample.aspx" title="Menu"  description="Menu Example" />
        <siteMapNode url="SiteMapPathExample.aspx" title="SiteMapPath"  description="SiteMapPath Example" />
        <siteMapNode url="TreeViewExample.aspx" title="TreeView"  description="TreeView Example" />
      </siteMapNode>
    </siteMapNode>
</siteMap>

How to use LoggedInTemplate and AnonymousTemplate in LoginView

LoggedInTemplate and AnonymousTemplate in LoginView Control
LoginView is an asp.net web server control. LoginView control displays the appropriate content template for a given user, based on the user authentication status and role membership.

The LoginView control includes two templated views that are displayed to the user. Those are AnonymousTemplate and LoggedInTemplate. AnonymousTemplate is displayed to the users who are not logged in. Anonymous users are those who are not logged in. LoggedInTemplete is displayed for logged-in users only. We can also create templates for the members of particular logged-in role groups.

The following asp.net example code demonstrates to us how can we create different templates for authenticated users and anonymous users in an asp.net application.

In the below example code, we created two templates view for authenticated users and anonymous users. When authenticated users visit the specified page, they can see a big image of a dolphin. And when anonymous users visit the page they can only see a smaller image version of the dolphin.
Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>LoginView control example: using LoggedInTemplate and AnonymousTemplate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>LoginView Example</h1>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <br /><br />
        <asp:LoginName ID="LoginName2" runat="server" FormatString="Hi {0}!" Font-Size="XX-Large" ForeColor="DeepPink" />
        <br />
        <asp:LoginView ID="LoginView1" runat="server">
            <LoggedInTemplate>
                <h2>Only LoggedIn user can see Big image</h2>
                <asp:Image ID="Image1" runat="server" ImageUrl="~/images/Dolphin.jpg" Width="486" Height="354" />
            </LoggedInTemplate>
            <AnonymousTemplate>
                <h2>Small image for Anonymous user.</h2>
                <asp:Image ID="Image1" runat="server" ImageUrl="~/images/Dolphin.jpg" Width="162" Height="118" />

            </AnonymousTemplate>
        </asp:LoginView>
    </div>
    </form>
</body>
</html>

How to use ChangePassword control in asp.net

ChangePassword Web Server Control
ChangePassword is an ASP.NET web server control. ChangePassword control enables website users to change the passwords they use to log in to the website.

ChangePassword server control uses the membership provider defined by the MembershipProvider property to change the password stored in the membership provider data store. ChangePassword control uses the default membership provider if a membership provider does not assign by web developers.

We can configure ChangePassword control to use email services to send the new password to the user. To send users a new password to their email address, we must configure an email server in the Web.config file for an ASP.NET application.

ChangePassword control has two states or views, the change password view and the success view. The change password view requests the current password and requires inputting the new password twice. The success views display confirmation that the password has been changed.

The following ASP.NET C# example code demonstrates to us how can we use ChangePassword web server control in an ASP.NET application.
ChangePasswordExample.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ChangePassword control example: how to change password in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LoginStatus ID="LoginStatus1"  runat="server"/>
        <br />
        <asp:LoginName ID="LoginName1" runat="server" FormatString="Hi {0}!" Font-Size="XX-Large" ForeColor="BurlyWood" />
        <br /><br />
        <asp:ChangePassword ID="ChangePassword1" runat="server" ></asp:ChangePassword>
    </div>
    </form>
</body>
</html>

How to login users programmatically in asp.net

Login user programmatically
In .net framework Membership class’s ValidateUser() method allows us to programmatically verify the supplied username and password are valid. The Membership class’s ValidateUser(username, password) method exists under the System.Web.Security namespace. This method requires passing two parameters.

The first parameter name is 'username' and another parameter name is 'password'. Both parameters’ data type is String. The username parameter value passes the name of the user to be validated and the password parameter value passes the password for the specified user. If the username parameter is null or empty then this method throws an HttpException.

This method returns a Boolean value. If the supplied username and password are valid then it returns True, otherwise, it returns false.

In this example code, we manually build a login page without Login server control. This login page contains two TextBoxes and a submit Button. Two TextBoxes uses to collect the user's username and password. Submit Button posts the form to the webserver to verify the user's credentials. This asp.net application is configured to use forms authentication and Membership class.

If the login form's supplied user credentials are invalid then login failed and a login failure message displays to the user. If the supplied credentials are valid then the user logged in programmatically and the user will be redirected to the originally requested URL.

FormsAuthentication class’s RedirectFromLoginPage() method allows us to redirect an authenticated user back to the originally requested URL or the default URL.

The following asp.net c# example code demonstrates to us how we can programmatically log in a user in an asp.net application.
Login.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        if (Membership.ValidateUser(TextBox1.Text.ToString(), TextBox2.Text.ToString()))
        {
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text.ToString(), false);
        }
        else {
            Response.Write("Input correct User Name and Password!");
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login Example: how to login users programmatically in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="User Name" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Password" AssociatedControlID="TextBox2"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Login" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>
Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Programmatically login example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Are you Logged in?</h1>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <br /><br />
        <asp:LoginName ID="LoginName2" runat="server" FormatString="Hi {0}! you are logged in." Font-Size="X-Large" ForeColor="DarkCyan" />
    </div>
    </form>
</body>

</html>

How to show login status in asp.net

LoginStatus Web Server Control
.NET framework LoginStatus Class allows us to detect the user's authentication state and toggles the state of a link to log in to or log out of a website. To allow users to log in to an ASP.NET application that uses forms authentication, we can use the LoginStatus server control to detect a user authentication status.

When this control found a user is not authenticated then it displays a Button to move the user to the login page. If the control found a login user then it displays a logout button for this user to log out from the website.

We can customize the default look and feel of LoginStatus control by setting its various properties such as BackColor, ForeColor, BorderStyle, BorderColor, BorderWidth, CssClass, Font, Height, Width, etc.

LoginStatus control's LoginImageUrl property allows us to set the URL of the image used for the login page link. LoginText property set the text display for the login link.

The LogoutText property set a text used for the log-out link. The LogoutPageUrl property set an URL for the logout page. The LogoutImageUrl property set an image URL to display as a logout Button. The LogoutAction property allows us to set a value that determines the action taken when a user logs out of a website with LoginStatus server control.

LoginName is an ASP.NET web server control that displays a user's login name if the user has logged in using asp.net membership. If the website uses integrated windows authentication then the LoginName control displays the user's windows account name.

The following ASP.NET example code demonstrates to us how can we show a user's login status in the ASP.NET application using LoginStatus web server control.
Login.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LoginStatus Control Example: How to show login status in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>My web site</h2>
        <asp:Login ID="Login1" runat="server" BackColor="#FFFBD6" BorderColor="#FFDFAD" 
            BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" 
            Font-Size="0.8em" ForeColor="#333333" TextLayout="TextOnTop">
            <TextBoxStyle Font-Size="0.8em" />
            <LoginButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" 
                BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" 
                ForeColor="#990000" />
            <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
            <TitleTextStyle BackColor="#990000" Font-Bold="True" Font-Size="0.9em" 
                ForeColor="White" />
        </asp:Login>
    </div>
    </form>
</body>
</html>
Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LoginStatus control example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Show Login Status</h1>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <br /><br />
        <asp:LoginName ID="LoginName2" runat="server" FormatString="Hi {0}!" Font-Size="XX-Large" ForeColor="Crimson" />
    </div>
    </form>
</body>
</html>

How to show login name in asp.net

Show login name in asp.net
LoginName is an ASP.NET web server control. LoginName control allows us to display a user's login name if the user has logged in using ASP.NET membership. If the site uses integrated windows authentication, the LoginName control displays the user's windows account name.

LoginName class allows us to display System.Web.UI.Page.User.Identity.Name property value. LoginName class exists in System.Web.UI.WebControls namespace.

LoginName control has many useful built-in properties to provide a better user experience such as AccessKey, BackColor, BorderColor, Attributes, BorderStyle, BorderWidth, CssClass, Font, ForeColor, FormatString, HasAttributes, Height, IsEnabled, Page, Parent, SkinID, Style, TabIndex, TagKey, ToolTip, ViewState, Visible, Width, etc.

LoginName control has a few events such as DataBinding, Disposed, Int, Load, PreRender, and Unload.

LoginName class’s FormatString property allows us to provide a format item string to display. FormatString property value data type is String. This value represents a string containing format items for displaying the user's name. The default value of the FormatString property is "{0}".

This FormatString property contains a standard text format string. the string "(0)" indicates where in the string the user's name is inserted. FormatString property throws a FormatException exception if the format String is not valid.

The following ASP.NET C# example code demonstrates to us how can we display the logged-in user's name on a web page using LoginName server control in an ASP.NET application.
Login.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LoginName Example: How to show login name in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8" 
            BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" 
            Font-Size="0.8em" ForeColor="#333333">
            <TextBoxStyle Font-Size="0.8em" />
            <LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" 
                BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
            <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
            <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em" 
                ForeColor="White" />
        </asp:Login>
    </div>
    </form>
</body>
</html>
Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Using LoginName Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Wellcome my site</h1>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <br />
        <asp:LoginName ID="LoginName1" runat="server" FormatString="{0} logged in." Font-Size="Medium" ForeColor="BlueViolet" />
        <br /><br />
        <asp:LoginName ID="LoginName2" runat="server" FormatString="Hi {0}!" Font-Size="XX-Large" ForeColor="Crimson" />
    </div>
    </form>
</body>
</html>

How to create Login page in asp.net

Login Web Server Control
In an asp.net application, we can create a user login page by using Login web server control. This Login control displays a user interface for user authentication. Login control renders two TextBoxes to input username and password. It also displays a CheckBox that allows users to indicate whether they want the server to store their identity for the next visit. It allows users to be automatically authenticated for the next visit.

The Login control has many useful built-in properties to customize it. We can change the default look and feel of the login page by using the Login control's BackColor, BorderColor, BorderWidth, BorderStyle, CheckBoxStyle, CreateUserIconUrl, CreateUserText, CreateUserUrl, CssClass, Font, ForeColor, FailureTextStyle, Height, HelpPageIconUrl, LayoutTemplate, TextBoxStyle, TitleTextStyle, LabelStyle, InstructionTextStyle, HyperLinkStyle, LoginButtonStyle, ValidatorTextStyle, BorderPadding, and many more properties. The Login control is fully customizable through templates and style settings.

This Login control is a composite control that renders all common user interface elements needed to authenticate a user in an asp.net application (website).

Login control's CreateUserText property allows us to set the text of a link to a registration page for new users. CreateUserUrl property set an URL for the new user registration page. DestinationPageUrl set an URL of the page displayed to the user when a login is successful.

DisplayRememberMe allows us to show or hide Remember Me checkbox from a login page. FailureText property allows us to set the text displayed when a login attempt fails. HelpPageUrl property set an URL for the login help page. InstructionText property set login instruction text for the user.

We also can change the default text of login control's elements by properties settings such as title text, remember me text, password label text, etc.

The following asp.net example code demonstrates to us how can we create a user login page using Login server control in an asp.net application.
Login.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login control Example: how to create Login page in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Login ID="Login1" runat="server"></asp:Login>
    </div>
    </form>
</body>
</html>
Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Using LoginStatus and LoginName Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Home page</h1>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <br /><br />
        <asp:LoginName ID="LoginName1" runat="server" FormatString="{0} logged in." Font-Size="Larger" ForeColor="Crimson" />
    </div>
    </form>
</body>
</html>

asp.net - How to submit a page to another page

Submit a page to another page in asp.net
The Button is an ASP.NET web server control. By default, a Button control is a submit Button, and by clicking the submit Button the ASP.NET page submits the page back to itself.

Sometimes ASP.NET developers want to post one page to another page. This is useful for creating multi-page forms. We can configure the Button control to post the current page to another page. This is called cross-page posting. We can also use Wizard server control to create multi-view forms. We can configure cross-page posting for individual Buttons, so we can create a page that posts to different pages depending on which Button the user clicks.

The Button control's PostBackUrl property gets or sets the URL of the page to post from the current page when the Button control is clicked. By default, this property value is an empty string that causes the page to post back to the same page. We need to set the target page URL as this property value when we want to cross-page posting.

We can get the information from the source page on the target page. The Page class has a property named PreviousPage. We can use the reference of the PreviousPage property to search the controls on the source page and extract their values. We can use here the FindControl() method.

The FindControl(String) method searches the naming container for a server control with the specified identifier. In this method, the String type parameter specifies the identifier for the control to be found such as a control's ID property value.

The following ASP.NET C# example code demonstrates to us how can we submit a web page to another page in an ASP.NET application.

In this example, at first, we created a web form name PostBackUrlExample.aspx and then we added two Label controls, two Button controls, and a RequiredFieldValidator control. In the first Button, we use a simple Click event which submits the page itself. In another Button, we use the PostBackUrl property to submit the page to another page named CityPage.aspx. When the user inputs a city name and clicks the second Button, the page submits to another page and the user can see inputted city name on the target page.
PostBackUrlExample.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "Your city name: " +
            TextBox1.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>PostBackUrl Example: how to submit a page to another page in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkSlateBlue"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Your City" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit in this page" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="Submit in city page" PostBackUrl="~/CityPage.aspx" />
    </div>
    </form>
</body>
</html>
CityPage.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        TextBox PP_TextBox1;
        PP_TextBox1 = (TextBox)PreviousPage.FindControl("TextBox1");
        Label1.Text = "Your City: " +
            PP_TextBox1.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>City Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>City Page</h1>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="Crimson"></asp:Label>
    </div>
    </form>
</body>
</html>

How to add an item to ListBox programmatically in asp.net c#

Add an item (ListItem) to ListBox
The following ASP.NET C# example code demonstrates to us how can we add an item to ListBox control programmatically at run time. ListBox is an ASP.NET list web server control. ListBox contains items collection. Each item of ListBox control represents a ListItem object. We can add ListItem object to ListBox control's items collection both statically and programmatically.

To add an item to ListBox control programmatically, we can call the Collection Class’s Add() method. This Add() method allows us to add an item to a collection. So we can easily add an item to the ListBox control as the Items Add(ListItem) method. Because ListBox contains an items collection that supports the addition of new items.

To Add an item (ListItem) to a ListBox control, first, we need to create the ListItem object. Each ListItem object has a Text property and optionally a Value property. We can also set the specified ListItem object Selected property value to true. After creating a ListItem object, we can add it to the ListBox control by calling Add() method.
ListBoxAddListItem.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        ListBox1.Items.Add(new ListItem(TextBox1.Text));
        Response.Write("Item Added: " + TextBox1.Text);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ListBox example: how to add ListItem dynamically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Controls" AssociatedControlID="ListBox1"></asp:Label>
        <asp:ListBox ID="ListBox1" runat="server">
            <asp:ListItem>Calendar</asp:ListItem>
            <asp:ListItem>Panel</asp:ListItem>
            <asp:ListItem>BulletedList</asp:ListItem>
            <asp:ListItem>AdRotator</asp:ListItem>
            <asp:ListItem>DropDownList</asp:ListItem>
            <asp:ListItem>ListBox</asp:ListItem>
            <asp:ListItem>Button</asp:ListItem>
        </asp:ListBox>
        <hr />
        <asp:Label ID="Label2" runat="server" Text="Input Item Text" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" Text="Add Item" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

How to use ValidationSummary control in asp.net

ValidationSummary web server control
ValidationSummary control allows us to display the summary of all validation errors. We can display validation errors summary inline of a web page or a message box or both by using ShowMessageBox and ShowSummary property value true or false. We can display validation messages as bulleted lists, single paragraphs, or only lists based on DisplayMode.

We can set a header text for the validation summary. ASP.NET ValidationSummary control has many properties to design the error messages text as fore color, back color, border color, border style, border width, theme, skin, and after all CSS class.

ValidationSummary allows a summary of all validation error messages from all validators in a single location. This example shows you how can we display all validation error messages as a summary using the ValidationSummary control.

Here we use three text boxes and make them required fields using RequiredFieldValidator control. When someone submits the form without entering TextBoxes value, he got a validation error message summary in one location as a bulleted list.
ValidationSummaryExample.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button_Submit_Click(object sender, System.EventArgs e)
    {
        Label_Message.Text = "Your submitted info....<br />" +
            "Name : " +
            TextBox_FirstName.Text.ToString() + " " +
            TextBox_LastName.Text.ToString() +
            "<br />City: " +
            TextBox_City.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to use ValidationSummary control in asp.net</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            How to use ValidationSummary control
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label_Message"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="OliveDrab"
            Font-Italic="true"
            Font-Size="X-Large"
            />
        <asp:ValidationSummary 
            ID="ValidationSummary1" 
            runat="server" 
            HeaderText="Following error occurs....." 
            ShowMessageBox="false" 
            DisplayMode="BulletList" 
            ShowSummary="true"
            BackColor="Snow"
            Width="450"
            ForeColor="Red"
            Font-Size="X-Large"
            Font-Italic="true"
            />
        <br /><br />
        <asp:Label 
            ID="Label_FirstName" 
            runat="server" 
            Text="First name" 
            AssociatedControlID="TextBox_FirstName"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="Navy"
            />
        <asp:TextBox 
            ID="TextBox_FirstName" 
            runat="server"
            Font-Bold="true"
            Font-Size="Large"
            Height="30"
            BackColor="Gold"
            Font-Names="Courier New"
            />
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator1"
             runat="server"
             ControlToValidate="TextBox_FirstName"
             ErrorMessage='Input your first name.'
             EnableClientScript="true"
             SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br /><br />

        <asp:Label 
            ID="Label_LastName" 
            runat="server" 
            Text="Last name" 
            AssociatedControlID="TextBox_LastName"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="Navy"
            />
        <asp:TextBox 
            ID="TextBox_LastName" 
            runat="server"
            Font-Bold="true"
            Font-Size="Large"
            Height="30"
            BackColor="Gold"
            Font-Names="Courier New"
            />
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator2"
             runat="server"
             ControlToValidate="TextBox_LastName"
             ErrorMessage='Input your last name.'
             EnableClientScript="true"
             SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br /><br />

        <asp:Label 
            ID="Label_City" 
            runat="server" 
            Text="City" 
            AssociatedControlID="TextBox_City"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="Navy"
            />
        <asp:TextBox 
            ID="TextBox_City" 
            runat="server"
            Font-Bold="true"
            Font-Size="Large"
            Height="30"
            BackColor="Gold"
            Font-Names="Courier New"
            />
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator3"
             runat="server"
             ControlToValidate="TextBox_City"
             ErrorMessage='Input your city.'
             EnableClientScript="true"
             SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br /><br />
        <asp:Button 
            ID="Button_Submit" 
            runat="server" 
            Text="Submit" 
            OnClick="Button_Submit_Click"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="DodgerBlue"
            Font-Names="Monaco"
            Height="45"
            Width="350"
            />
        <br /><br />
    </div>
    </form>
</body>
</html>

ASP.NET - Using SetFocusOnError property in validation control

Set focus on error in validation
The following asp.net c# tutorial code demonstrates how we can set the focus on error in validation. In this tutorial, we used the RequiredFieldValidator control to validate TextBox. In the RequiredFieldValidator web server control, we set focus on the error feature. The RequiredFieldValidator web server control makes the associated input control a required field.

The RequiredFieldValidator SetFocusOnError property gets or sets a value that indicates whether the focus is set to the control specified by the ControlToValidate property when validation fails.

The SetFocusOnError property value is a Boolean. This property value is true to set focus on the control specified by ControlToValidate when validation fails otherwise its value is false. The default is false. So the asp.net c# developers can enable focus on error feature by using this SetFocusOnError property in validation control. They just have to set the SetFocusOnError property value to true.

The asp.net c# developers can use the SetFocusOnError property to specify whether focus is automatically set to the control specified by the ControlToValidate property when this validation control fails. This allows the web page user to quickly update the appropriate control. If multiple validation controls fail and this property is set to true then the control specified in the ControlToValidate property for the first validation control receives focus.
ValidationSetFocusOnError.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "Your Country: " +
            TextBox1.Text.ToString() +
            "<br />City: " +
            TextBox2.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Validation example: using SetFocusOnError property in validation control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkTurquoise"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Country Name" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator1"
             runat="server"
             ControlToValidate="TextBox1"
             ErrorMessage="Input Country Name!"
             SetFocusOnError="true"
             >
        </asp:RequiredFieldValidator>
        <br />

        <asp:Label ID="Label3" runat="server" Text="City Name" AssociatedControlID="TextBox2"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator2"
             runat="server"
             ControlToValidate="TextBox2"
             ErrorMessage="Input City Name!"
             SetFocusOnError="true"
             >
        </asp:RequiredFieldValidator>
        <br />

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

ASP.NET Validation - How to disable client script

Disable client script in validation
The following asp.net c# tutorial code demonstrates how we can disable the client script in validation. In this tutorial, we used a RequiredFieldValidator control to validate a TextBox. In the RequiredFieldValidator web server control, we disabled the client script. The RequiredFieldValidator web server control makes the associated input control a required field.

The RequiredFieldValidator EnableClientScript property gets or sets a value indicating whether client-side validation is enabled. The EnableClientScript property value is a Boolean. This property value is true if client-side validation is enabled otherwise the value is false. The default value is true.

So, using this EnableClientScript property, the asp.net developers can disable the client script while validating the web page. They just have to set this property value to false.

The asp.net c# developers can use the EnableClientScript property to specify whether client-side validation is enabled. By default, this property value is set to true which enables client-side validation if the browser supports it. The developers can disable client-side validation on a control-by-control basis.

The asp.net Validation controls always perform validation on the server. Asp.net also has a complete client-side implementation that allows DHTML-supported browsers.
DisableClientScript.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "Your City: " +
            TextBox1.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Validation example: how to disable client script</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkBlue"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="City Name" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator1"
             runat="server"
             ControlToValidate="TextBox1"
             ErrorMessage="Input City Name!"
             EnableClientScript="false"
             >
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit City" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

asp.net c# RadioButtonList control example

RadioButtonList control example
RadioButtonList is an ASP.NET list web server control. RadioButtonList control renders a group of radio button controls where each radio button shares the same group name. RadioButtonList control encapsulates a radio group. RadioButtonList control each ListItem object is renders a single radio button control.

RadioButtonList control's items exist in an items collection. So we can manage (edit, insert, and delete) RadioButtonList item collection by the .NET framework's Collection Class methods and properties.

RadioButtonList control has many built-in properties to design and style the control itself such as BackColor, ForeColor, CssClass, etc. We also can customize its items level style by core CSS style such each different colors for different items.

RadioButtonList control's AutoPostBack property and SelectedIndexChanged event allow us to quickly get the user's item selection after each time the RadioButtonList selection has changed.

In the following example code, we populated a RadioButtonList control with items by declarative syntax in the tag section. We also keep the AutoPostBack property value to 'True' and write an event handler for its SelectedIndexChanged event.

So when users change the RadioButtonList item selection we caught the selection on the SelectedIndexChanged event handler section and display an image on the web page which is specified by RadioButtonList present selected item.

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e) {
        Image1.ImageUrl = "Images/" + RadioButtonList1.SelectedItem.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>RadioButtonList simple example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Select for view image"></asp:Label>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" RepeatColumns="2" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true">
            <asp:ListItem>ScotlandFlower.jpg</asp:ListItem>
            <asp:ListItem>ArtificialOrchid.jpg</asp:ListItem>
            <asp:ListItem>CacaoFlower.jpg</asp:ListItem>
            <asp:ListItem>Flower.jpg</asp:ListItem>
        </asp:RadioButtonList>
    </div>
    </form>
</body>
</html>

How to use MultiView control in asp.net

MultiView and View Server Control
MultiView is an asp.net web server control. The View control is also an asp.net web server control. But view control always is contained within multiview control. Both multiview and view control act as a container for other controls and markup. Only one view can be defined as an active view in MultiView. MultiView ActiveViewIndex property specifies the active view within view collections of a multiview. Only active view control is rendered to the page.

We can navigate views by setting the multiview ActiveViewIndex property value. ActiveViewIndex property holds the specified view's index number. MultiView control can include navigation buttons that we can add to each view.

We can create a navigation button by adding any Button, LinkButton, or ImageButton server control to each view. For that, we need to set the CommandName and CommandArgument properties of each view. Reserved CommandName values are NextView, PrevView, SwitchViewByID, and SwitchViewByIndex. NextView and PrevView corresponding CommandArgument have no values. SwitchViewByID CommandArgument value is the ID of the view to switch to. SwitchViewByIndex CommandArgument value is the index number of the view to switch to.

You can create a multi-page form using MultiView and view controls. But Wizard control is better for creating a multiple-page form that needs to fill step by step. MultiView and view control provide support similar to Wizard control. The Wizard has more built-in UI elements than multiview control. So MultiView is a better choice if we want to display a view based on condition rather than sequence.

The following example source code demonstrates to us how can we use MultiView and view controls in asp.net. In this web form, we create a multiview control and five view controls within it. Each view displays a beautiful image using Image server control. We also put a button control on each view to navigate views. When the user clicks the navigation button, the MultiView control displays the next view.
MultiView.aspx

<%@ Page Language="C#" %><!DOCTYPE html><script runat="server">    protected void Page_Load(object sender, System.EventArgs e) {        if(!Page.IsPostBack){            MultiView1.ActiveViewIndex = 0;           }    }    void NextImage(object sender, System.EventArgs e)    {        MultiView1.ActiveViewIndex += 1;    }    protected void Page_PreRender(object sender, System.EventArgs e) {        Label1.Text = "Beautiful birds images : " +            (MultiView1.ActiveViewIndex + 1).ToString() +            " of " + MultiView1.Views.Count.ToString();    }</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>How to use MultiView control in asp.net</title></head><body style="padding:25px">    <form id="form1" runat="server">    <div>        <h2 style="color:MidnightBlue; font-style:italic;">                  How to use MultiView        </h2>              <hr width="450" align="left" color="Gainsboro" />        <asp:Label            ID="Label1"            runat="server"            Font-Bold="true"            Font-Names="Comic Sans MS"            ForeColor="Crimson"            Font-Italic="true"            Font-Size="X-Large"            />        <br /><br />        <asp:MultiView ID="MultiView1" runat="server">            <asp:View ID="View1" runat="server">                <asp:Image                     ID="Image1"                     runat="server"                     ImageUrl="~/Images/birds1.jpg"                    Height="300"                    />                <br />                <asp:Button                     ID="Button1"                     runat="server"                     Text="Next Image"                     OnClick="NextImage"                    Font-Bold="true"                    ForeColor="Navy"                    Height="45"                    Width="150"                    />            </asp:View>            <asp:View ID="View2" runat="server">                <asp:Image                     ID="Image2"                     runat="server"                     ImageUrl="~/Images/birds2.jpg"                    Height="300"                    />                <br />                <asp:Button                     ID="Button2"                     runat="server"                     Text="Next Image"                     OnClick="NextImage"                    Font-Bold="true"                    ForeColor="Navy"                    Height="45"                    Width="150"                    />            </asp:View>            <asp:View ID="View3" runat="server">                <asp:Image                     ID="Image3"                     runat="server"                     ImageUrl="~/Images/birds3.jpg"                    Height="300"                    />                <br />                <asp:Button                     ID="Button3"                     runat="server"                     Text="Next Image"                     OnClick="NextImage"                    Font-Bold="true"                    ForeColor="Navy"                    Height="45"                    Width="150"                    />            </asp:View>            <asp:View ID="View4" runat="server">                <asp:Image                     ID="Image4"                     runat="server"                     ImageUrl="~/Images/birds4.jpg"                    Height="300"                    />                <br />                <asp:Button                     ID="Button4"                     runat="server"                     Text="Next Image"                     OnClick="NextImage"                    Font-Bold="true"                    ForeColor="Navy"                    Height="45"                    Width="150"                    />            </asp:View>            <asp:View ID="View5" runat="server">                <asp:Image                     ID="Image5"                     runat="server"                     ImageUrl="~/Images/birds5.jpg"                    Height="300"                    />            </asp:View>        </asp:MultiView>    </div>    </form></body></html>

How to use TreeView in asp.net

TreeView Server Control
TreeView is an asp.net web server control. TreeView displays hierarchical data such as a table of contents or files directory, in a tree structure. TreeView control is made up of nodes. We can display static data in a TreeView by creating a collection of TreeNode elements as children of the TreeView.

We can bind TreeView to a data source such as XmlDataSource and SiteMapDataSource. TreeView can also be bound to an XmlDocument object or a DataSet object.

TreeView node types are the parent node, child node, leaf node, and root node. The Parent node contains other nodes. child node is contained by another node and the leaf node have no children node. The root node is not contained by any other node.

Node has two properties Text and Value. text property value displayed in the browser and the value property is hidden in the browser and stores any additional data about the node. a node can have one mode selection mode or navigation mode. selection mode is the default. NavigateUrl property used in navigation mode.

We can customize the TreeView appearance. We can apply CSS or inline styles. TreeView can be designed by the following node styles HoverNodeStyle, LeafNodeStyle, NodeStyle, ParentNodeStyle, RootNodeStyle, and SelectedNodeStyle. TreeView also has basic design properties such as BackColor, ForeColor, BorderStyle, BorderColor, BorderWidth, Width, Height CssClass, EnableTheming, SkinID, ExpandDepth, ImageSet, etc.

We can customize images that are displayed in TreeView by using the following properties CollapseImageUrl, ExpandImageUrl, LineImagesFolder, and NoExpandImageUrl.

TreeView control provides many events such as TreeNodeCheckChanged, SelectedNodeChanged, TreeNodeExpanded, TreeNodeCollapsed, TreeNodePopulate, and TreeNodeDataBound.

When the user clicks a node, it can either raise a selection event via a postback. Or it goes to another page if the NavigateUrl property is set. If the NavigateUrl property is not set, then the node clicking raises the SelectedNodeChanged event.

The following example source codes describe you to learn more about TreeView control.
~/App_Data/ASPNETControls.xml

<?xml version="1.0" encoding="utf-8" ?>
<ToolBox>
  <Item Name="Standard Toolbox Controls">
    <Option Control="AdRotator" />
    <Option Control="BulletedList" />
    <Option Control="CheckBox" />
    <Option Control="FileUpload" />
    <Option Control="MultiView" />
  </Item>
  <Item Name="Data Toolbox Controls">
    <Option Control="ListView" />
    <Option Control="GridView" />
    <Option Control="LinqDataSource" />
    <Option Control="XmlDataSource" />
  </Item>
  <Item Name="Validation Toolbox Controls">
    <Option Control="CompareValidator" />
    <Option Control="CustomValidator" />
  </Item>
  <Item Name="Navigation Toolbox Controls">
    <Option Control="Menu" />
    <Option Control="SiteMapPath" />
    <Option Control="TreeView" />
  </Item>
</ToolBox>
Now create a Web Form name TreeView.aspx. Then add an XmlDataSource Control and a TreeView Control. For XmlDataSource Control's DataFile uses the AspNetControls.xml file and for TreeView Control's DataSourceID uses the XmlDataSource Control's ID. Then uses the asp:TreeNodeBinding to bind the XML file's data. Here is the source code of TreeView.aspx file.
TreeView.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to use TreeView in asp.net</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            How to use TreeView
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:XmlDataSource 
            ID="XmlDataSource1" 
            runat="server" 
            DataFile="~/App_Data/ASPNETControls.xml"
            >
        </asp:XmlDataSource>
        <asp:TreeView 
            ID="TreeView1" 
            runat="server" 
            DataSourceID="XmlDataSource1"
            >
            <DataBindings>
                <asp:TreeNodeBinding 
                    DataMember="ToolBox" 
                    Text="ASP.NET ToolBox"
                    />
                <asp:TreeNodeBinding 
                    DataMember="Item" 
                    TextField="Name"
                    />
                <asp:TreeNodeBinding 
                    DataMember="Option" 
                    TextField="Control"
                    />
            </DataBindings>
        </asp:TreeView>
    </div>
    </form>
</body>
</html>

How to validate a DropDownList in asp.net

DropDownList Validation
DropDownList is an asp.net list web server control that allows us to select a single item from a drop-down list at a time. DropDownList control contains ListItem objects. The following asp.net c# example code demonstrates to us how can we validate a DropDownList control in a web form.

When users submit a form without changing the selection of DropDownList items, then the first item is posted to the server as a selected item if there is no initial selected item. Normally web developers put an instruction-only item at the DropDownList items top such as an item with the text 'select an item' etc. So web developers need to ensure that users select an item from DropDownList control other than the first item. We can validate a DropDownList server control using the RequiredFieldValidator control.

RequiredFieldValidator is an asp.net validation server control that makes the associated input control a required field. We can make the DropDownList input control a required field by attaching it with a RequiredFieldValidator control.

To do this we need to set the RequiredFieldValidator ControlToValidate property value to DropDownList control's ID which dropDropDownList downlist control we want to validate. RequiredFieldValidator control's InitialValue property gets or sets the initial value of the associated input control. In this example code, the DropDownList initial value is 'Choose One', because we set this text for the DropDownList control's first item Text property value. The initial value is only used for information only, users need to select any one item from the DropDownList control other than it.

RequiredFieldValidator ErrorMessage property gets or sets the text for the error message displayed in a ValidationSummary control or the RequiredFieldValidator control itself when validation fails.
DropDownListValidation.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "Your selected item is : " +
            DropDownList1.SelectedItem.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to validate a DropDownList in asp.net</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            DropDownList Validation
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label1"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="ForestGreen"
            Font-Italic="true"
            Font-Size="X-Large"
            />
        <br /><br /><br />
        <asp:DropDownList 
            ID="DropDownList1" 
            runat="server"
            Width="350"    
            Font-Size="X-Large"    
            Font-Names="Comic Sans MS"
            ForeColor="MidnightBlue"
            BackColor="FloralWhite"
            >
            <asp:ListItem Selected="True">Choose One</asp:ListItem>
            <asp:ListItem>BulletedList</asp:ListItem>
            <asp:ListItem>Button</asp:ListItem>
            <asp:ListItem>Calendar</asp:ListItem>
            <asp:ListItem>DataGrid</asp:ListItem>
            <asp:ListItem>DataList</asp:ListItem>
            <asp:ListItem>DataPager</asp:ListItem>
        </asp:DropDownList>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator1"
             runat="server"
             ControlToValidate="DropDownList1"
             InitialValue="Choose One"

             ErrorMessage="* Please select an item."
             ForeColor="Red"
             Font-Names="Impact"
             >
        </asp:RequiredFieldValidator>
        <br /><br />
        <asp:Button 
            ID="Button1" 
            runat="server" 
            Text="Validate DropDownList" 
            OnClick="Button1_Click"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="DodgerBlue"
            Font-Names="Monaco"
            Height="45"
            Width="350"
            />
    </div>
    </form>
</body>
</html>

ASP.NET CompareValidator - How to validate Data Type

Validate data type using CompareValidator
The CompareValidator class compares the value entered by the user in an input control with the value entered in another input control or with a constant value.

The following asp.net c# tutorial code demonstrates how we can validate a data type using CompareValidator. In this example code, we will validate the integer data type. We will check the user input an integer value for the age field or not using the CompareValidator.

The CompareValidator ControlToCompare property gets or sets the input control to compare with the input control being validated. This property value is a String which is the input control to compare with the input control being validated. The default value is Empty.

The asp.net c# developers have to use the ControlToCompare property to specify an input control, such as a TextBox control, to compare with the input control being validated.

The CompareValidator Operator property gets or sets the comparison operation to perform. This property value is one of the ValidationCompareOperator values. The default value is Equal.

The ValidationCompareOperator Enum specifies the validation comparison operators used by the CompareValidator control. In this example, we set this property value to DataTypeCheck. The DataTypeCheck is a comparison for data type only.

The CompareValidator Operator property throws ArgumentOutOfRangeException if the specified comparison operator is not one of the ValidationCompareOperator values. For the CompareValidator Type property value, we set the Integer to validate the data type.
CompareValidatorExample.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender,System.EventArgs e){
        Label1.Text = "Form Submited. Your value is Integer";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>CompareValidator example: how to validate Data Type in asp.net</title>
    </head>

    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server" Font-Size="Larger" ForeColor="DarkCyan"></asp:Label>
                <br />

                <asp:Label ID="Label2" runat="server" Text="Age" AssociatedControlID="TextBox1"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareFieldValidator1" runat="server" ControlToValidate="TextBox1" Operator="DataTypeCheck" Type="Integer" ErrorMessage="Input valid age">
                </asp:CompareValidator>
                <br />

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

How to use CompareValidator control in asp.net

CompareValidator
CompareValidator control compares user inputted value with another input control value or a constant value. CompareValidator validation success if the inputted value matches the criteria specified by the Operator, ValueToCompare, or ControlToCompare property.

CompareValidator Type property indicates whether inputted value needs to be converted to a specified data type (string, date, currency, double, or integer). The controlToValidate property indicates which control needs to validate. ControlToCompare property indicates which control needs to compare with inputted value (such as TextBox value).

ValueToCompare property indicates that you want to compare the inputted value with a constant value instead another control value. Don't put ControlToValidate and ValueToCompare properties together in a CompareValidator control. You can use any one property at a time. That means you can only compare with a control or compare with a constant value at the same time.

You can use the Operator property to specify the type of comparison to perform, such as equal to, greater than, equal, not equal, less than, less than equal, data type check, etc. Operator property value DataTypeCheck validated the data type specified by the Type property. so the CompareValidator validation fails if the inputted value cannot be converted to the specified data type.

This example demonstrates how can we compare (validate) to the password field (TextBox) using the ASP.NET CompareValidator control. If the user-inputted password does not match in both TextBoxes then the validation fails and the browser shows a validation error message. If both TextBox text matches then validation success.
CompareValidatorHowToUse.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender,System.EventArgs e){
        Label1.Text = "Form Submited and Password match.";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>CompareValidator example: how to use CompareValidator control in asp.net</title>
    </head>

    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <br />

                <asp:Label ID="Label2" runat="server" Text="<u>P</u>assword" AccessKey="P" AssociatedControlID="TextBox1"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareValidator" runat="server" ControlToValidate="TextBox1" ControlToCompare="TextBox2" ErrorMessage="Password does not match!">
                </asp:CompareValidator>
                <br />

                <asp:Label ID="Label3" runat="server" Text="Re-Type Password" AssociatedControlID="TextBox2"></asp:Label>
                <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
                <br />

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

How to use RadioButtonList control in asp.net c#

RadioButtonList web server control
ASP.NET RadioButtonList control enables the user to select an item from the list. RadioButtonList supports data binding programmatically from the database. We can also populate it manually by inputting a list of items inside the RadioButtonList tag. RadioButtonList is a single selection radio button group. RadioButtonList has an item collection. We can determine which item is selected by testing its SelectedItem property.

We can change RadioButtonList design by setting up its various property as like BackColor, BorderColor, BorderStyle, BorderWidth, CellPadding, CellSpacing, CssClass, Font-Bold, Font-Italic, Font-Names, Font-Overline, Font-Size, etc. there are more three properties RepeatColumns, RepeatDirection, and RepeatLayout which help you to place list item vertically or horizontally.

RadioButtonList has standard AutoPostBack property. As with other list control, RadioButtonList has an excellent event SelectedIndexChanged. So that when someone selects an item it automatically posts back to the page and we can determine programmatically which item is selected now. For that, we need to set the AutoPostBack property value to true and set up a SelectedIndexChanged event. DataSourceID, DataTextField, and DataValueField property help you to data bind RadioButtonList with the database. RadioButtonList also supports theme and skin.

In this example we demonstrate a very simple example of RadioButtonList. Select an item from RadioButtonList and submit the form by clicking Button control. You will get which item is selected from RadioButtonList.
RadioButtonListHowToUse.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Text ="You Selected Collection: " + RadioButtonList1.SelectedItem.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>RadioButtonList example: how to use RadioButtonList control in asp.net</title>
    </head>

    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="Crimson"></asp:Label>
                <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                    <asp:ListItem>ColdFusion</asp:ListItem>
                    <asp:ListItem>Asp.Net</asp:ListItem>
                    <asp:ListItem>PHP</asp:ListItem>
                </asp:RadioButtonList>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Show Selected Software" OnClick="Button1_Click" />
                <hr />

            </div>
        </form>
    </body>
</html>

How to use RadioButton control in asp.net c#

RadioButton web server control
The RadioButton control lets you make a group of radio buttons with other RadioButton. If you set its GroupName property to the same for multiple radio buttons then all radio buttons with the same name act as a single group. Within a group, you can only select one RadioButton at a time. RadioButton group work as like RadioButtonList. With RadioButton control you can more customize it than RadioButtonList items.

Back color, border color, border style, font names, font bold, font italic, fore color (text color), and much more property help you to design RadioButton. It also supports CSS class, theme, and skin. Even validation works with RadioButton control. RadioButton has an AutoPostBack property and a CheckChanged event. By using those features you can determine immediately which RadioButton is selected from a group.

This example uses a RadioButton group with two RadioButton. Here we assign the AutoPostBack property value to true and set up a CheckChanged event. When you select a RadioButton from this group, the web browser shows which RadioButton is selected (checked).
RadioButtonHowToUse.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void RadioButton_CheckedChanged(object sender,System.EventArgs e) {
        if (RadioButton1.Checked == true)
        {
            Label1.Text = "Your selected item is : " +
                RadioButton1.Text;
        }
        else {
            Label1.Text = "Your selected item is : " +
                RadioButton2.Text;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>How to use RadioButton control in asp.net</title>
    </head>
<body style="padding:25px">
    <form id="form1" runat="server">
        <div>
            <h2 style="color:MidnightBlue; font-style:italic;">      
                How to use RadioButton control
            </h2>      
            <hr width="450" align="left" color="Gainsboro" />
            <asp:Label
                 ID="Label1"
                 runat="server"
                 Font-Bold="true"
                 Font-Names="Comic Sans MS"
                 ForeColor="Crimson"
                 Font-Italic="true"
                 Font-Size="X-Large"
                />
            <br /><br />
            <asp:Label
                 ID="Label2"
                 runat="server"
                 Text="Choose an item..."
                 Font-Bold="true"
                 Font-Names="Book Antiqua"
                 Font-Size="Larger"
                 Font-Underline="true"
                />
            <br />
            <asp:RadioButton 
                ID="RadioButton1" 
                runat="server" 
                Text="ASP.NET" 
                GroupName="Software" 
                AutoPostBack="true" 
                OnCheckedChanged="RadioButton_CheckedChanged"
                Font-Bold="true"
                Font-Names="Courier New"
                Font-Size="XX-Large"
                ForeColor="Navy"
                />
            <asp:RadioButton 
                ID="RadioButton2" 
                runat="server" 
                Text="ColdFusion"
                GroupName="Software" 
                AutoPostBack="true" 
                OnCheckedChanged="RadioButton_CheckedChanged"
                Font-Bold="true"
                Font-Names="Courier New"
                Font-Size="XX-Large"
                ForeColor="Navy"
                />
        </div>
    </form>
</body>
</html>