Wednesday, 28 December 2011

How To set Default Button for ENTER key pressed event, and How To set Focus on a particular Control when Page loads, and How To Shift Focus from One Control To Another when TAB key is pressed

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1"  runat="server" defaultbutton="Button1" defaultfocus="TextBox1">
    
<asp:TextBox ID="TextBox1" Text="Focus1" runat="server" TabIndex="1"> <asp:TextBox ID="TextBox2" Text="Focus2" runat="server" TabIndex="2"> <asp:TextBox ID="TextBox3" Text="Focus3" runat="server" TabIndex="3"> <asp:TextBox ID="TextBox4" Text="Focus4" runat="server" TabIndex="4"> <asp:Button runat="server" ID="Button1" Text="DefaultClick-IfPressed-EnterKey" OnClick="DefaultButtonClicked"/> <asp:Button runat="server" ID="Button2" Text="ClickExplicitly" OnClick="ExplicitlyClicked"/>
</form> </body> </html> 
 
 
if you are using master page then you have to do like this
m  
my master page source:
 <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>
my content page source:
 <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
my content page code behind: 
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Form.DefaultButton = Button1.UniqueID;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("ha ha click me ");
    }
}

No comments:

Post a Comment