.Net Tip: Default Button for Enter Key

I don’t know if I should be happy to now know about this, or just conserned that it’s taken me this long to discover. But one issue that surfaces time and time again when programming in ASP.NET, is that issue that pressing enter/return in a text feild doesn’t always do what you want it to do. 

On a normal website you can have many forms each with their own submit button which becomes the default action when pressing return on one of the forms feilds. However in ASP.NET Web Forms there is only ever one form on a page, but there could be 10 different buttons each needing to be the default action for a particular text box. 

The solution as it turns out is very simple and you have two options both introduced in .NET 2.0 (yes that’s how old it is!) 

1. Default button for the form. If your page has more than one button, but there is only one that you want to fire when you hit enter then in the code behind you can just type… 

Form.DefaultButton = Button1

or it can also be specified in your aspx file 

<form runat="server" defaultbutton="Button1">

2. If you need to be more specific a panel can also have a default button… 

Panel1.DefaultButton = Button1

or again is can be specified in your aspx file

<asp:Panel runat="server" DefaultButton="Button1">

Master Page Error

If you’re like me you may have gone into design mode in visual studio 2010 hoping to do some work only to be greeted with the following message.

Which initially is a bit confusing, as your site may have just run without any problems. But even so you go to check the placeholders anyway and they look fine. Then you copy and paste the ID’s out of the Master Page just to be sure, but still no luck. Check through the Master Page itself and that also looks fine, no squiggly lines to be seen. Finally create a new WebForm linked to the master page, but even this gives the same error.

Now if you have the problem I had, look at the title tag in the Master Page. Does it say <title /> or <title></title>? If it’s the first then that’s your issue. By default VS2010 will put in the correct tag, but if like me you’ve just slapped in some HTML from an old project or from a PSD conversion that’s been done for you, then chances are you may end up overwriting the title tag as well.