How to set the first few characters of a WinForms TextBox to Read-Only?
I have a form with a textbox on it that is used to enter a URL. I need to add (http://) as a predefined value to this textbox and want it to be read only so the user won't be able to remove the http:// but he can write after it.
Any help would be highly appreciated.
Here are a few options:
The easy way is to just create a label outside the text box (to the left) with those characters. (simple and easy to understand for the user)
Create a second readonly text box to use at the start, style it to match the input one and align them next to each other. Yes, you will get a single pixel line to split them both, but I think this will add to the user experience to make it obvious this is not for messing with (I would personally choose this option)
If you need the style you can roll your own user control that uses a panel, label and textbox with appropriate border styling set as needed. (best way to get the exact style you need)
The fourth, more annoying way, would be to handle one of the key events (such as KeyDown) on the textbox itself. With this you can do numerous checks and alter the caret position to make it work, but trust me this will do your head in trying to get it working perfectly! (way too much hard work to get right)
To summarise, I think option 2 is the best here. Of course if you were using WPF you would undoubtedly have a lot more flexibility in styling.
Have you considered placing a label beside it with "http://" as the text? and then when accepting the users input you can just append the "http://" with your textbox.Text.
Here is another idea:
On every backspace press, count the number of characters in your textbox. If it is == 7, then ignore the backspace. If it is greater, then check the number of characters after the backspace. If the number of characters is less than 7, clear the textbox and reset the text.
private void a_keyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)8)
{
if (myTextbox.Text.Length == 7)
// do stuff..
}
else if //do stuff...
}
You could also not even display the http:// and just append it to the Textbox.Text code. Check first that it doesn't start with that as well.
To clarify my last remark:
string sURL = txtURL.Text.StartsWith("http://") ? txtURL.Text : "http://" + txtURL.Text;