October 25, 2011

.NET Search and Replace Dialog


I was tasked to enhance an existing application. The feature that was wanted was a search and replace dialog like the one in notepad. The notepad search and replace dialog is quite simple and maybe I'll just create a clone for that immediately but then I thought .NET would have a "built-in" dialog for this that I can just call. I checked my VS 2005 (at my office -- yeah we're still old school :[ ) if there is one somewhere in the common dialogs.

I was not able to find one. So, I fired up Google and I came to this article.
So I found out that there is but unfortunately .NET does not have its "managed counterpart". There are two options that I can choose, try to check if I can P/Invoke this dialog or just implement my own. My instinct told me to just create my own version but it should be closer to the notepad search and replace dialog. I also wanted it to be readily available to other applications also and it should have a simple interface like maybe a single line will do and the dialog's code will just do the rest. So I proceeded with my own version.
I was able to achieve my goal, fortunately. I can use it in my other applications by just a single line of code. With this single line of code (C#):

         SearchReplaceDialog.AttachTo(textBox);

I have a search and replace feature (but yes, only notepad-like). You can download the full source code here.
Some important things that I made:

  • It is implemented as a lazy Singleton class. It is only instantiated once the AttachTo static method is called.
  • It is activated by Ctrl+F/Ctrl+H.
  • Any TextBoxBase control can be attached.
  • The codes are tightly coupled. I will have to separate the functionality from the UI codes but until I am pushed to that, that will have to wait (sounds like XP :D).