0

I have been working on Web Forms for many months, but today I encountered a problem.

I have e.g. 2 buttons on form Save. Next, when a user fills out the form and presses Enter, it should trigger the SAVE button.

I tried a lot like

this.Page.Form.DefaultButton = btnSave.UniqueID; 
this.Page.Form.DefaultFocus = btnSave.ClientID;

but it didn't work.

Please help me on this. I have tried many codes, but none of them actually worked.

protected void Page_Load(object sender, EventArgs e)
{
    // 2 lines of code, for setting Save as a default
    // button upon page loading so hitting Enter will
    // trigger SAVE button.
    this.Page.Form.DefaultButton = btnSave.UniqueID;
    this.Page.Form.DefaultFocus = btnSave.ClientID;

    if (Session.Count <= 0)
    {
        Response.Redirect("login.aspx");
    }

    lblMsgPopUp.Visible = false;
}
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
user3518032
  • 423
  • 8
  • 25
  • This looks correct to me, and I have been able to make your code work in Chrome and Firefox. What specific error(s) or problem(s) do you get? What "didn't work"? – J0e3gan Jul 10 '14 at 07:16
  • when i click on textbox than it takes away focus from save button. – user3518032 Jul 10 '14 at 07:40
  • Well, yes, that is to be expected. Setting the default (i.e. initial) focus on `btnSave` won't prevent the focus from shifting to a text box or other input that is clicked. What happens when you press Enter? – J0e3gan Jul 10 '14 at 07:47
  • it submits value upon pressing – user3518032 Jul 10 '14 at 08:04
  • That is also to be expected. It sounds like this is working exactly like it should. What do you want it to do differently? – J0e3gan Jul 10 '14 at 08:09
  • 1
    see, problem is that i have 4 textboxes, e.g. i enter text into first textbox and accidently press enter than it triggers Enter, i want it to trigger enter upon reaching last textbox only – user3518032 Jul 10 '14 at 08:14
  • 1
    This assumes that the 4th text box will always be the last one in which the user provides input. It sounds like you would be better off using client-side validation to cancel a submit when Enter is pressed prematurely. – J0e3gan Jul 10 '14 at 08:28

1 Answers1

3

The code you have is fine. I checked it in Chrome and Firefox so as not to miss anything by just reading it.

If you want btnSave to only trigger a save when Enter is pressed and the form is complete, I suggest using client-side validation to ensure that the form is complete, cancel the submit and alert the user if it is not etcetera.

See another SO question about client-side validation and cancellation of a submit if you need help with that.

Community
  • 1
  • 1
J0e3gan
  • 8,740
  • 10
  • 53
  • 80