Admin Admin

Number of posts: 206 Registration date: 2007-01-01
 | Subject: Avoid unexpected postback after pressing Enter in textbox Tue Jan 15, 2008 7:08 am | |
| How to avoid unexpected postback after pressing Enter in textbox Easy Way:1)Goto you page / Master Page, where the form tag is ex. | Code: | <form id="formNew" runat="server"> |
2)Now on Page_Init or OnInit - Make the Hidden Button your default button
| Code: | protected void Page_Init(object sender, EventArgs e) {
formNew.DefaultButton = ""; }
|
PS: You may still need to Handle the on Enter button as below and make it do nothing
How to Handle on Enter:
Below Example is if you have a master page, and are trying to access the OnEnterEvent from the child pages / contents / controls.
For a single simple page. Read point 1) , 2) , 3) and 5) . Replace with your code in 3) , for whatever you want the event handler to do
1)Goto you page / Master Page, where the form tag is
ex.
| Code: | <form id="formNew" runat="server"> |
2)Create a New Image Button at the top of the page (just after the form tag) on the page like below, and make its width and height as 0 px and width as 0 px, and give it an ImageUrl (important)
ex.
| Code: | <asp:ImageButton ID="HiddenButton" runat="server" OnClick="HiddenButton_Click" width="0px" Height="0px" ImageUrl="whatever.jpg" />
|
3)In the code behind, Create the HiddenButton_Click event handler
ex.
| Code: | protected void HiddenButton_Click(object sender, EventArgs e) { SubmitForm(sender,e); return; } |
4)Create an OnSubmitForm event handler, in the code behind
| Code: | public EventHandler OnSubmitForm;
/// <summary> /// On Enter Key Press AnyWhere in the Form /// </summary> public void SubmitForm(object sender, EventArgs e) { if(OnSubmitForm != null) { OnSubmitForm(sender, e); } }
|
5)Now on Page_Init - Make the Hidden Button your default button
| Code: | protected void Page_Init(object sender, EventArgs e) {
formNew.DefaultButton = HiddenButton.ID; }
|
6) Read this step Incase you have a master page (ex. NormalMaster.master)
In your child page / contents / control add the below code to Handle the OnEnterEvent
| Code: | protected override void OnInit(EventArgs e) { base.OnInit(e);
NormalMaster masterPage = (NormalMaster)(Page.Master); masterPage.OnSubmitForm += [CREATE NEW EVENT HANDLER]; }
|
|
|