Solved

ASP.NET - Default button when user hits [Return]

Posted on 2004-04-06
25
44,467 Views
Last Modified: 2011-08-18
I need a simple way to make a particular (image)button on a web form fire when the user presses the return key, please.
 
0
Comment
Question by:sumo_the_cat
  • 9
  • 7
  • 2
  • +7
25 Comments
 
LVL 19

Expert Comment

by:Desp
ID: 10764502
Source :
http://www.utmag.com/September2003/Page3.asp



private void Page_Load(object sender,
    System.EventArgs e)
{
   // This causes the page to associate Enter
   // key with btnSearch click.
   Page.RegisterHiddenField( "__EVENTTARGET",
       "btnSearch" );
}

Note
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10764715
In VB.NET, this should work, right?

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Set default button to btnSearch.
        Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")

    End Sub

I doesn't, though. Any ideas why? (there is certainly more than one textbox on the form, although one of them is yellow for no reason whatsoever.)
Thanks,
Pete.
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10765687
>> although one of them is yellow for no reason whatsoever
Do you have a Google toolbar?  if so Check the Google Toolbar Options and turn off AutoFill. The toolbar checks for fields that look like likely candidates for autofill and highlights them.  
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10766460
Clever! Nice one dfiala13. You can have some extra points! I would have wasted days on that, in all likelihood. But do you know why the reason why the above isn't working?
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10766479
On a similar (completely unrelated!) note, do you how to get rid of all the double spacing on my web forms? It's really annoying, but I want to use flow layout. I'll post extra points outside this q.
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10766862
>> But do you know why the reason why the above isn't working?
Good question.  I'll see if I can see what's what.

>>double spacing on my web forms
What do you mean?  I use flowlayout all the time.
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10767432
Well, when I press enter to start a new line, I get large gaps in between each line.
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10767440
OK, Though it would be nice if were that easy
Reason  Page.RegisterHiddenField( "__EVENTTARGET",
       "btnSearch" );
 won't work because

the script has no idea what to do with it.  If you look at your html source after the page renders you won't see anything referencing it (unless perhaps you have some validators turned on -- but even then it won't work because it will get overwritten in the validation script).

No, you need to do some keycapture in javascript and have it set the event target and tnen call the submit when the enter key is pressed.
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10767479
The VS designer is throwing <p> tags around each line.  You can either change the default style of the <p> or simply remove them or don't use the designer for entering long text blocks.
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10768806
Don't know Jscript... This must be a common requirement - surely there's a way to do it?

This should be a different thread, but i guess it's "line-height" that i need to change. But to what value? visual studio is only suggesting 'Normal'.
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10769226
>>This must be a common requirement - surely there's a way to do it?
There is -- Javascript.  This is all client-side behavior.

You capture the enter key down event and call the form submit. Here's an example...

http://dotnetjunkies.com/WebLog/darrell.norton/archive/2004/03/03/8374.aspx

You can also attempt to set the tab order.  First button in the tab order "usually" gets the default submit

you can change the line height to a value in pixels line-height: 15px.  
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10770285
I've had a look at that URL before, but left feeling confused. Will it work with imagebuttons? Can you tell me exactly what to do to get it to work in VS.NET with VB.NET? Java confuses the heck out of me, being an MS Access programmer by heart.
0
 
LVL 12

Accepted Solution

by:
dfiala13 earned 450 total points
ID: 10771623
Sure it will work with imagebuttons.

And remember its not Java, its Javascript, which is just a handy way to deal with client-side events on an HTML page.  ASP.NET makes extensive use of it for the validation controls and most third party custom controls are loaded with it.  So time to get unscared, because if you want to get the most out of ASP.NET (or any web development tool) you are going to have to at least get comfortable with Javascript.  Otherwise your developing will be severely handicapped.

We'll skip the script regsitering for now and do it the brute force way...

Put this in the HTML of your page, somewhere between the header tags...

<SCRIPT language=""javascript"">

<!--

function fnTrapKD(btn, event){

 if (document.all){

  if (event.keyCode == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if (document.getElementById){

  if (event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if(document.layers){

  if(event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

}

// -->

</SCRIPT>

All this does is capture the enter key.  All the if-else stuff is because not all browsers are created equal they all have different ways of identifying elements (which is a royal pain).

Now, add this method to your code-behind or your VB script.  This will add an onkeydown trap to every text control you send to it...

Private Sub SetDefaultButton( txt as TextBox, defaultButton as ImageButton )
 txt.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");


End sub

Finally, in your Page_load event handler, add a call to the method for each text box you have. It will set the default button to use for every textbox.  You can use the same button for each textbox or different ones.

SetDefaultButton(TextBox2, Button2)

That's all there is to it. Hit the enterkey and submit.

0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10773462
That works perfectly. Some points for you my friend:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20946265.html

Is there a way to capture "form"-wide events? I'd like to have an application-wide toolbar which uses the function keys as shortcuts. Is this possible, and could it be incorporated with this solution?

I've ballsed up my <P> tags though! I'll have to start again.
0
 
LVL 2

Assisted Solution

by:davisg090767
davisg090767 earned 50 total points
ID: 10774608
I might be wrong here but I think you can press ctrl-M or shift-M instead of the return key in Flow layout which inserts <br> instead of <p>, Give it a try I'm sure that worked for me.
0
 
LVL 12

Assisted Solution

by:dfiala13
dfiala13 earned 450 total points
ID: 10775383
>>Is there a way to capture "form"-wide events?
You can try to add a onkeydown trap to the body element...

<body onkeydown="return MyTrap(event);">

and add a script similar to the one above to deal with it.  Of course to really make it useful, you'd want to put it in a user control and have it alter the body element on whatever page it was put on.
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10788041
davisg090767: that just inserts <P>s, but thanks for telling me about the <br> tag - that gives me a new line with no space.

I'm going to need some help with all this formatting business, especially tags. VB.NET is fine, but I'm finding this web stuff much more fiddly than I'd expected..!

I can't work out how to change the double line-spacing in between the <P></P> tags. I don't want double, but single isn't much use either when a small gap is needed.

I will post another question though.

Thanks for all the help. dfiala13, you know your stuff.
0
 
LVL 2

Author Comment

by:sumo_the_cat
ID: 10788066
0
 

Expert Comment

by:susanh02
ID: 10943906
Thanks for the solution!  It was really helpful.

If you know you want the same default button behavior for all TextBox controls in your page, you can iterate over the Controls.  This takes less typing than adding it manually for all text boxes.  (C#)

            public void SetDefaultButtons( Button button )
            {
                  foreach ( Control control in this.Controls )
                  {
                        if ( control is TextBox )
                        {
                              SetDefaultButton((TextBox)control, button);
                        }
                  }
            }

0
 

Expert Comment

by:groggyjava
ID: 11283503
holding down the shift key in design mode inserts a line-break and not a new paragraph
it works almost all microsoft products, macromedia and a bunch of others, too.
0
 

Expert Comment

by:groggyjava
ID: 11283507
correction: holding down the shift key WHILE YOU HIT ENTER inserts ...
0
 

Expert Comment

by:steveexmet
ID: 13315365
Hi, in relation to the posting by "dfiala13" for this solution mine doesnt work, when im in my textbox i still get a  server roundtrip rather than the javascript function been invoked ?.  i have looked at the source after the page as rendered and the onkeydown attribute has been added suceesfully from C# - onkeydown="fnTrapKD(Datechange)" - so this is ok, but in this function all i have now is an alert statement and even that doesnt get triggered, its like the page/browser is overriding the added attribute. any ideas
steve
0
 

Expert Comment

by:jisarp3
ID: 21977676
If you ahve a panel on the page it has a DefaultButton you can set


0
 

Expert Comment

by:amkbailey
ID: 22748476
This is the simple way to do this: In your VB.NET code just add this code below to your Page_Load subroutine.

Me.frm.DefaultButton = Me.but.ID

Where 'frm' is the name of your form in the your ASPx page and 'but' is the name of your button.
0
 

Expert Comment

by:sunultrasparc
ID: 24316795
For other newbs  like me if your not working with an imagebutton make sure you change your routine to the correct button type.

example below

Private Sub SetDefaultButton( txt as TextBox, defaultButton as Button )
 txt.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");
End sub

Worked Great, Thanks for your hard work!!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question