|Delphi Clinic||C++Builder Gate||Training & Consultancy||Delphi Notes Weblog||Dr.Bob's Webshop|
Set Focus to a Control in ASP.NET with Delphi 2005
The past few weeks, I've been working on a little ASP.NET project in Delphi 2005 (migrating from IntraWeb 5.x), and I've had to "invent" some techniques that in retrospect also might be useful to share with other ASP.NET developers - using Delphi 2005, Delphi 8 for .NET or any other .NET development language or environment for that matter.
First of all, there were a few pages where a DropDownList was used (with a set of values). The application needed to respond directly if a new selected item in the DropDownList was picked. That was easy enough by setting the AutoPostBack property of the DropDownList to True, writing some event handling code in the DropDownList_SelectedIndexChanged method. Although this indeed performed a round-trip to the (web) server, the downside was that the focus on the DropDownList was lost. Which may not sound like a big deal, but can quickly become a major annoyance if you just want to scroll down in the DropDownList, see the changes of the new choice, and after every change have to click on the DropDownList again to give it the focus.
<form id="frmWhatever" runat="server">When you're done, make sure that there is a declaration of the following form in your ASP.NET Page class definition:
frmWhatever: System.Web.UI.HtmlControls.HtmlForm;For some reason, the Delphi 2005 HTML Designer doesn't always produce this declaration for me. Obviously a more useful name than frmWhatever can be used here, but you get the idea.
Assuming you want to use this code in more than one place in your application, it's even more generic to put the code in a special routine. In the Delphi 2005 Code Editor, select the code we've just written (shown above), right-click with the mouse and from the Refactoring menu select "Extract Method". This will produce the following dialog:
You may want to change the constant definition for CRLF to a simple #13#10 afterwards (and you may also want to change the order of the arguments, but that's only a matter of taste).
With a little manual reformatting, the final routine can be seen below:
The method SetFocus can now be called for any control on your form. An example where I called it is as follows (first passing the Form's ID, then the control ID):
For an even more useful method, you can also pass the Page itself, and move the entire routine outside the TWebForm1 class - for example in its own WebUtils unit (but that's left as exercise for the reader).
Using the AutoPostBack property on ASP.NET controls like a DropDownList will ensure that you can do a round-trip to the server whenever the selected item is changed. Normally, however, the DropDownList would not regain the focus when the page is displayed again, something which can be quite annoying (especially if you want to quickly browse through the alternatives listed in the DropDownList).