文本框与按键关联

当我们在开发Web应用程序的时候,时常碰到textbox和button相关联的时候(如登录、搜索)但是要么用鼠大哥要么tab多次才能到button。
以下的方法可以直接Enter.
……
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

……
……

 public static void TieButton(Page page, Control TextBoxToTie, Control ButtonToTie)
    {
        //
        string strJS= "";

        //检查button的类型并确定js字符串。
        if (ButtonToTie is LinkButton)
        {
            strJS= "if((event.which && event.which == 13)||(event.keyCode && event.keyCode == 13)){" + page.ClientScript.GetPostBackEventReference(ButtonToTie, "").Replace(":", "$") + ";return false;} else return true;";
        }
        else if (ButtonToTie is ImageButton)
        {
            strJS = "if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){" + page.ClientScript.GetPostBackEventReference(ButtonToTie, "").Replace(":", "$") + ";return false;} else return true;";
        }
        else
        {
            strJS = "if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {document." + "forms[0].elements['" + ButtonToTie.UniqueID.Replace(":", "_") + "'].click();return false;} else return true;";
        }

        //两种控件类型。
        if (TextBoxToTie is HtmlControl)
        {
            ((HtmlControl)TextBoxToTie).Attributes.Add("onkeydown", jsString);
        }
        else if (TextBoxToTie is WebControl)
        {
            ((WebControl)TextBoxToTie).Attributes.Add("onkeydown", jsString);
        }
    }

OK了,绑定某个textbox Or control,现在我们在输入的时候随时都可以Enter了。

作者:SCPlatform
Email:SCPlatform@outlook.com
本文旨在学习、交流使用,任何对文章内容的出版、印刷,对文章中提到的技术的商业使用时,请注意可能存在的法律风险。

原文地址:https://www.cnblogs.com/SCPlatform/p/962597.html