Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the first few characters of a WinForms TextBox to Read-Only?

Tags:

c#

.net

winforms

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.

enter image description here

Any help would be highly appreciated.

like image 401
Rafik Bari Avatar asked Jun 14 '12 14:06

Rafik Bari


People also ask

How do I make a textBox ReadOnly in Windows Forms?

Set the TextBox control's ReadOnly property to true . With the property set to true , users can still scroll and highlight text in a text box without allowing changes.

How do you make a textBox not editable in C#?

You can try using: textBox. ReadOnly = true; textBox.


1 Answers

Here are a few options:

  1. 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)

  2. 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)

  3. 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)

  4. 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.

like image 63
musefan Avatar answered Sep 28 '22 08:09

musefan