Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a WinForms TextBox with a RichTextBox

I have a windows forms application that contains a TextBox. I would like to do a blanket replace of a particular TextBox with a new RichTextBox. If I delete the TextBox in question from the designer, won't Visual Studio 2012 automatically delete any code that references the textbox?

Is there a way to do this gracefully without jeopardizing the code that is already there?

I'm supposing that one way is to do a string replace in the cs files, including even, the Designer.cs files and find any strings that contain the control's name (txtQuestion) and replace it with the name of the new RichTextBox control.

I was hoping Visual Studio would have a simpler way to do this.

like image 412
Su Llewellyn Avatar asked Sep 28 '22 09:09

Su Llewellyn


1 Answers

I'm not aware of a truly simple way to do this. That said, doing it manually should not be very complicated:

  • In the *.Designer.cs file, there should be just two places to change the type: the field declaration, and where the new instance is created. Just change the type name from TextBox to RichTextBox there.
  • There is not actually any need to change the name of the control (i.e. the name of its field), but if you really want to, you can just change the Name property in the control's Properties window, and VS will automatically refactor the code referring to that field. Any code referring explicitly to that control's field will automatically be updated.
  • If you're really unlucky, you'll have some places in the code where you cast an object reference to the control to its actual type, e.g. in an event handler where you use the sender parameter instead of just referring to the field (something that happens when e.g. the same event handler is used with more than one control). Those places, you will have to track down yourself and change the cast and variable to which it's assigned to the correct type. Note that it's not like the IDE would have a practical way of reliably doing that work anyway.

There are few if any members of TextBox that aren't just inherited from or overrides of members of TextBoxBase, the base class shared between TextBox and RichTextBox, so all of the code actually using the field which is now a RichTextBox ought to "just work". I can't think of any possible exceptions off the top of my head, but if they exist they should be very few, and will be easy to find simply by compiling the code.

It's possible a tool like Resharper could make some of the above easier. I'm not sure…I don't use it myself. But if the above seems too onerous, you might look to see if they have a trial version and see if it helps in this scenario.

like image 120
Peter Duniho Avatar answered Nov 06 '22 03:11

Peter Duniho