Solved

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

Posted on 2004-04-06
25
44,427 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
Comment Utility
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
Comment Utility
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
Comment Utility
>> 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
 
LVL 2

Author Comment

by:sumo_the_cat
Comment Utility
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
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 12

Accepted Solution

by:
dfiala13 earned 450 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
0
 

Expert Comment

by:susanh02
Comment Utility
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
Comment Utility
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
Comment Utility
correction: holding down the shift key WHILE YOU HIT ENTER inserts ...
0
 

Expert Comment

by:steveexmet
Comment Utility
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
Comment Utility
If you ahve a panel on the page it has a DefaultButton you can set


0
 

Expert Comment

by:amkbailey
Comment Utility
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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now