Simon Miller Team : Web Development Tags : Web Development

Better formatting in Visual Studio 2010

Simon Miller Team : Web Development Tags : Web Development

By default Visual Studio’s formatting of code is not as elegant as it could be. I like to be pedantic about the layout of my code as it makes it more readable for me and other developers who have to work on the same projects that I do.

For starters, many people are not aware of the ‘auto-format’ shortcut key combination which in ‘Web Developer’ profile is Control K + D and in other profiles may be Control E + D. This will re-format your code – be it C#, ASP/HTML or CSS – to the standards defined in Visual Studio options.

However, many of the defaults are illogical or may simply not be suited to your needs. The first one that I change is the CSS formatting rules from “Expanded” to “Compact”. This changes your CSS from this:

To this:

The formatting is not limited to CSS.  You can get many visual improvements by editing the default HTML and ASPx control layouts.


If a tag is not present in the Tag Specific Options list you can simply add it. Visual Studio likes to insert a line break after the opening tag for headings i.e. h1, h2. By adding the tag to the specific options list you can customise its closing tag (if one is required or if the tag self-closes) and most importantly how it will handle line breaks. You can see in the example below that I have added a h1 tag to the options list, set it to close with a separate tag and set the line breaks to before and after. Other options are before, within and after a tag (good for div’s) or no line breaks at all (good for hyperlinks, images etc.

The best part about formatting ASPx controls is you can remove the needless separate closing tag that is, by default, inserted on the majority of .NET controls. Literals, for example, never need a separate closing tag. In the same dialog, navigate to the ASP.NET controls menu and add asp:Literal to the list. Select self-closing tag and line breaks after tag only and you will get a much cleaner code layout.

Optimising your code layout is addictive but more importantly portable. You can migrate your settings from an older version of Visual Studio or take your settings to another computer. Read here for more information.