views:

1231

answers:

4

Hi, i have a few text boxes and buttons on my form.

Lets say txtBox1 is next to btnSubmit1, txtBox2 is next to btnSubmit2, txtBox3 is next to btnSubmit3.

How can i set the focus on btnSubmit3 when the user starts to type something in txtBox3. Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.

Please Help Regards Etienne

+4  A: 

If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms:

<asp:Panel id="panel1" runat="server" DefaultButton="Button1">
   <asp:TextBox id="textbox1" runat="server" />
   <asp:Button id="Button1" runat="server" Text="Button 1" />
</asp:Panel>

<asp:Panel id="panel2" runat="server" DefaultButton="Button2">
   <asp:TextBox id="textbox2" runat="server" />
   <asp:Button id="Button2" runat="server" Text="Button 2" />
</asp:Panel>

<asp:Panel id="panel3" runat="server" DefaultButton="Button3">
   <asp:TextBox id="textbox3" runat="server" />
   <asp:Button id="Button3" runat="server" Text="Button 3" />
</asp:Panel>
vimpyboy
Great stuff!! Thanks!!
Etienne
A: 

Use JavaScript and add a "onblur" for those TextBoxes...

Example:

<asp:TextBox ID="t1" runat="server" onblur="CheckIfTextBox1ShouldFocusOnButton1();" />

:)

Timothy Khouri
MMM, what must i place inside my CheckIfTextBox1ShouldFocusOnButton1();
Etienne
A: 

I've seen it done like this but don't ask me to explain it or to say what the pros and cons are over any other method. Just thought I would publish it in case its useful to you.

// Fires a particular event when enter is pressed within a textbox.
function FireButtonOnEnter(controlID)
{
    if((event.which ? event.which : event.keyCode) == 13)
    {
     window.event.returnValue = false;
     window.event.cancelBubble = true;
     document.getElementById(controlID).click();
    }
}

Call it by adding the following for the textbox...

txtOrgName.Attributes.Add("OnKeyDown", String.Format("return FireButtonOnEnter('{0}');", btnOrgNameGo.ID));
Si Keep
A: 

This is an easy solution if you know that the only browser being used is IE.

You just have to add to the Page load

txtBox1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnSubmit1.UniqueID + "','')");

txtBox2.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnSubmit2.UniqueID + "','')");

txtBox3.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnSubmit3.UniqueID + "','')");

The reason that this only works in IE is that it uses the Javascript "event" key word that doesn't work in Firefox.

Avitus
Hi, this does not work.....is it the same code for the VB.NET? I know i must leave the ";" out.
Etienne