How do I have text in a winforms textbox be prefix

2019-08-22 06:11发布

问题:

I have an application that allows the creation and running of automated testing scripts. The test scripts themselves are xml files that are meant to be portable, which means that once one is configured it should work on any computer.

One of the configuration settings saved in the xml files is the location of builds to copy over. Depending on the setup of the computer root folder can be different, for example on my computer I may be looking at F:\Builds\2-QA\ClientA where as another machine it requires \\server1\Public\Builds\2-QA\ClientA, and if the server changes it would be `\newserver\Public\Builds\2-QA\ClientA'.

I solve this descrepency by only having the user save the last part (e.g. 2-QA\ClientA) in the xml, and the root is resolved by an application setting in App.Config.

The problem with this is that in the GUI where the user enters the application source directory, it's not clear what part of the folder structure they have to enter and what is resolved by App.Config.

Therefore, what I would like is my textbox to have the root directory auto-populated inside, but in a read-only way. So for instance, the textbox will display F:\Builds\ and the user can add the folder structure they want at the end, but they cannot delete any part of the F:\Builds\. When saving I intend to strip off the F:\Builds\ part, but that can't be relied upon if they are able to (intentionally or not) delete characters from F:\Builds\.

Any suggestions on accomplishing this?

回答1:

Try using a MaskedTextBox and set its Mask property to the string you want prefixed.

Something like: F:\Builds\LLLLLLLLLLLL



回答2:

My thought:

Forget about making it unmodifiable.

Have a function that runs on text change. If the prefix is N characters long, change the first N characters of the text box to the prefix.



回答3:

Could you add a label in front of the text box. The label would contain the text you wouldn't want changed which makes it clear to the user that you want the next bit entered into the text box.