Page Tips

  1. Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down. In ASP.NET 2.0 you can simply add the MaintainScrollPostionOnPostBack attribute to the Page directive:
    <%@ Page Language="C#" MaintainScrollPositionOnPostback="true" %>

Form Tips

  1. Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Using the DefaultFocus property of the HtmlForm control you can easily do this:

    <form id="frm" DefaultFocus="txtUserName" runat="server">
  2. Set the default button that is triggered when the user hits the enter key: This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.

    <form id="frm" DefaultButton="btnSubmit" runat="server">


Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control. Notice that the "$" is used to delimit the nesting:

<form id="form1" DefaultFocus="formVw$txtName" runat="server">     <div>        <asp:FormView ID="formVw" runat="server">           <ItemTemplate>              Name:              <asp:TextBox ID="txtName" runat="server"                 Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />           </ItemTemplate>        </asp:FormView>     </div> </form>

This little trick can also be used on the server-side when calling FindControl():

TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox; if (tb != null) {     //Access TextBox control }