I can hardly believe it has taken me this long, several few years in fact, to discover just how few ASP.NET Web Forms controls need an explicit ID attribute. I mean even the default kind of ID value assigned by the designer, e.g. TextBox4, Label7, DropDownList1 and other such abominations; in common or garden data binding scenarios most of these aren’t necessary at all.

This pleases me. It pleases me no end, because I have finally been relieved of my tortuous obsession for reassigning meaningful ID attributes to controls, like renaming TextBox1 to surnameText, etc. If you have any idea how just seeing those default IDs laying around in markup makes me, read on. If you actually write code against such IDs, you may stop reading though, and step outside to be shot.

I quite by accident discovered I can simply delete most of these. Data bound controls don’t need them and controls that raise events don’t need them. That’s why we have object sender in our events after all. We can simply delete them when they pop up, and only worry about a meaningful ID if we are going to use it, i.e., if it is really going to be meaningful. It is, however, quite the pain to do this manually every time I create or paste a control (VS is considerate enough that it provides one if you thoughtlessly paste a server-side tag without an ID attribute. Enter the macro!

Every time my eyes are offended by the encroaching masses of default IDs, I run this little baby, and it removes any ID attribute that ends in a number. Yes, there may be some casualties one day, but it is unlikely I will hand-code control IDs that require a numbered ID attribute; collateral damage if you will, but I’m happy to accept that and move on. This Macro code carries no warranties, only warnings, but try it if you, like me, like neat code.

Sub RemoveDefaultIds()

DTE.Windows.Item_
     (“{CF2DDC32-8CAD-11D2-9302-005345000000}”).Activate() ‘Find and Replace
DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
DTE.Find.FindWhat = ” ID=”".#:z”"”
DTE.Find.ReplaceWith = “”
DTE.Find.Target = vsFindTarget.vsFindTargetFiles
DTE.Find.MatchCase = True
DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
DTE.Find.SearchPath = “Current Document”
DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResults1
Debug.Print(DTE.Find.Execute())
DTE.Windows.Item_
    (“{CF2DDC32-8CAD-11D2-9302-005345000000}”).Close() ‘Find and Replace

End Sub

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"