Powered by Blogger.

Monday, November 6, 2017

How to call button click event on press enter key in asp.net?



In this asp.net blog we will discuss how we can set default submit button on enter key in asp.net web application. If I will give an real world example, here I have a textbox and a search button. I want to make the search button as default button, so that when user put something in the search textbox and press enter then the button click code should execute.

In some other cases you might noticed that, in most of the modern web sites, there will be a search textbox but there will be no button. User just needs to press enter. Here we will see how we can achieve both the things in asp.net web sites.

Example With Button:
In this case let us take a asp.net button, textbox and one label and it looks like below:

<asp:Label ID="lblResult" runat="server" Text=""></asp:Label><br />
                <asp:TextBox ID="txtSearch" runat="server" Height="30px" Width="280px"></asp:TextBox><br />

                <asp:Button ID="btnSearch" runat="server" Text="Search" Style="display: none" OnClick="btnSearch_Click" />

Now to set the default button here as btnSearch. take an asp.net panel control and set the DefaultButton as btnSearch and the full code looks like below:

<asp:Panel runat="server" DefaultButton="btnSearch">
                <asp:Label ID="lblResult" runat="server" Text=""></asp:Label><br />
                <asp:TextBox ID="txtSearch" runat="server" Height="30px" Width="280px"></asp:TextBox><br />
                <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
            </asp:Panel>

Now when I run the asp.net web site and write something in the search textbox and press enter, it will execute the button click code and will display like below.
asp.net submit button enter key

Example Without Button:
In the other case when we do not need to show the button, we can just use Style="display: none" to hide the button. So the full code will looks like below:

 <asp:Panel runat="server" DefaultButton="btnSearch">
                <asp:Label ID="lblResult" runat="server" Text=""></asp:Label><br />
                <asp:TextBox ID="txtSearch" runat="server" Height="30px" Width="280px"></asp:TextBox><br />
                <asp:Button ID="btnSearch" runat="server" Text="Search" Style="display: none" OnClick="btnSearch_Click" />
            </asp:Panel>

call button click event on press enter key in asp net

Also you can read some asp.net articles:

- Download Programming ASP.NET MVC 5 book pdf free

- How to to show or hide textbox based on checkbox using jQuery in asp.net?

Hope this asp.net article may be will helpful.





0 comments

Post a Comment