Tuesday, August 31, 2010

Button Server Control

by Emmaneale Mendu, Web Developer

Another common control for your Web forms is a button that can be constructed using the Button server control. Buttons are the usual element used to submit forms.

The Button control's OnClick event

protected void Button1_Click(object sender, EventArgs e)
{
//Code Here
}

The Button control is one of the easier controls to use, but there are a couple of properties of which you must be aware: Causesvalidation and CommandName. They are discussed below.

CausesValidation Property

If you have more than one button on your Web page and you are working with the validation server controls, you don't want to fire the validation for each button on the form. Setting the CausesValidation property to False is a way to use a button that will not fire the validation process.

CommandName Property
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 id="Head1" runat="server">
    <title>Button Control Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" CommandName="1" runat="server" Text="Button1" />
        <asp:Button ID="Button2" CommandName="2" runat="server" Text="Button2" />
        <asp:Button ID="Button3" CommandName="3" runat="server" Text="Button3" />
    </div>
    </form>
</body>
</html>
The Button Command Event

protected void Button_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "1":
Response.Write("Button 1 is Clicked");
break;
case "2":
Response.Write("Button 2 is Clicked");
break;

default :
Response.Write("Button 3 is Clicked");
break;
}
}

Buttons That Work with Client-Side JavaScript
Buttons are frequently used for submitting information and causing actions to occur on a Web page.

You can create a page that has a JavaScript event, as well as a server-side event, triggered when the button is clicked, as shown below.

<!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 Example</title>
<script type="text/javascript" language="javascript">
function AlertHello(){
alert('Hello Emmaneale');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" OnClientClick="AlertHello()" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

No comments:

Post a Comment