Attaching a Button_Click event occurs when you press enter in a ASP.NET TextBox
<asp:Panel ID="PanelSearch" runat="server" DefaultButton="ButtonSearch">
<asp:TextBox ID="TextBoxSearch" runat="server" />
<asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />
</asp:Panel>
<asp:Panel ID="PanelSearchResults" runat="server">
<asp:Literal ID="LiteralSearchResults" runat="server"></asp:Literal>
</asp:Panel>
Code-behind:
/// <summary>
/// Event that occurs when you click ButtonSearch,
/// or when you press enter on TextBoxSearch
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ButtonSearch_Click(object sender, EventArgs e)
{
String searchResults = String.Empty;
if(TextBoxSearch.Text!="")
{
String searchItem = TextBoxSearch.Text;
int numbersOfResult = GetNumbersOfResult(searchItem);
if (0 == numbersOfResult)
searchResults = "No items were found";
else
searchResults = String.Format("{0} items found", numbersOfResult);
LiteralSearchResults.Text = searchResults;
// Other code ...
}
}
- Wrap the TextBoxSearch and ButtonSearch in an <asp:Panel ID="PanelSearch
- Set the DefaultButton property of the PanelSearch to the ID of button, in the case of the example ButtonSearch.
- Write the necessary code, inside the method ButtonSearch_Click( ... )