Wednesday, March 23, 2011

Panel.DefaultButton property with LinkButton control in ASP.NET

Using Panel.DefaultButton property with LinkButton control in ASP.NET

LinkButton as the DefaultButton fix for ASP.Net

As we know that the the asp.net have many limitations.One of them very common is that we can only make asp button as deafult for a panel not LinkButton.But we know that linkbutton is better in the sense of its CSS implementation but we can't make this as default button when a user want to save their data on Press Enter.

So here i will so you how to overcome this problem with simple example.

Just place the following class into your App_Code folder.

 

Then on page where you want to implement this just add the following directive-

<%@ Register Namespace="CustomLinkButton" TagPrefix="CC" %>

And now do what you want into a panel like-

<asp:text box..........................blah blah

 <asp:Panel runat="server" ID="Pnl_login" DefaultButton="lnkLogIn">

  <CC:LinkButtonDefault ID="lnkLogIn" runat="server" CssClass="fromBtn" ValidationGroup="LogIn"

                                OnClick="lnkLogIn_Click"><Span style="cursor:pointer;">Login</Span></CC:LinkButtonDefault>

</asp:Panel>

  Now if you hit enter after writing some text into the textboxes,you will see that the linkbutton onclick event "lnkLogIn_Click" will fire.

So here is the solution .Enjoy your coding..............

//#################Class for custom Linkbutton###################

//Please add this class into your app code folder

using System;

using System.Web.UI.WebControls;

using System.Web.UI;



/// <summary>

/// Summary description for CustomLinkButton

/// </summary>

namespace CustomLinkButton

{

    public class LinkButtonDefault : LinkButton

    {

        protected override void OnLoad(System.EventArgs e)

        {

            ScriptManager.RegisterStartupScript(this.Page, GetType(), "addClickFunctionScript", _addClickFunctionScript, true);



            string script = String.Format(_addClickScript, ClientID);

            ScriptManager.RegisterStartupScript(this.Page, GetType(), "click_" + ClientID,

                script, true);

            base.OnLoad(e);

        }



        private const string _addClickScript = "addClickFunction('{0}');";



        private const string _addClickFunctionScript =

            @"  function addClickFunction(id) {{

            var b = document.getElementById(id);

            if (b && typeof(b.click) == 'undefined') b.click = function() {{

                var result = true; if (b.onclick) result = b.onclick();

                if (typeof(result) == 'undefined' || result) {{ eval(b.getAttribute('href')); }}

            }}}};";

    }

}

//#################End of Class for custom Linkbutton#############

No comments:

Post a Comment