Search This Blog

Sunday, September 2, 2007

Handle 'Enter' event in ASP.NET

Problem:

I have two form, search form and login form.

  1. When i keyin username and password and hit enter in Mozilla Firefox. The search form will be trigger.
  2. When i keyin a search key in search key form, validator for login form will be trigger

Form details:

  1. Search form:
    • 1 textbox
    • 1 button
  2. Login form:
    • 2 textbox
    • 2 validator
    • 1 image button

To solve the problem:

  1. Add a panel with defaultbutton for both form.

    <asp:Panel ID="pnlLogin" runat="server" defaultbutton="IbtnLogin">
    <asp:TextBox ID="username" runat="server"></asp:TextBox>
    <asp:TextBox ID="password" runat="server"></asp:TextBox>
    <asp:ImageButton ID="IbtnLogin" runat="server" ImageUrl="~/img/LoginButton.gif" OnClick="IbtnLogin_Click" />
    </asp:Panel>


  2. Set RequiredFieldValidator Enabled = false

    <asp:RequiredFieldValidator ID="vdtUsername" runat="server" ErrorMessage="Enter username" ControlToValidate="username" Enabled="False"></asp:RequiredFieldValidator>
    <asp:RequiredFieldValidator ID="vdtPassword" runat="server" ErrorMessage="Enter password" ControlToValidate="password" Enabled="False"></asp:RequiredFieldValidator>

    Enable the RequiredFieldValidator in IbtnLogin_Click
    IbtnLogin_Click(object sender, ImageClickEventArgs e)
    {
    vdtUsername.Enabled = true;
    vdtPassword.Enabled = true;
    .......................................................
    .......................................................
    .........................................
    }

problem solved!

No comments: