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

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.


Something like this?

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    var textBox = sender as TextBox;

    if (!textBox.Text.StartsWith("http://"))
    {
        textBox.Text = "http://";
        textBox.Select(textBox.Text.Length, 0);

    }
}

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;

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

Tags:

C#

.Net

Winforms