Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanent prefix in a TextBox

Tags:

c#

winforms

I am trying to have a permanent prefix input in the textbox. In my case, I want to have the following prefix:

DOMAIN\

So that users can only have to type their username after the domain prefix. It's not something I have to do, or pursue but my question is more out of curiosity.

I was trying to come up with some logic to do this on the TextChangedEvent however, this means I need to know which characters have been deleted where and then pre-append DOMAIN\ to whatever their input is - I can't work out the logic for this so I can't post what I have tried apart from where I got to.

public void TextBox1_TextChanged(object sender, EventArgs e)
{
  if(!TextBox1.Text.Contains(@"DOMAIN\")
  {
    //Handle putting Domain in here along with the text that would be determined as the username
  }
}

I've looked on the internet and can't find anything, How do I have text in a winforms textbox be prefixed with unchangable text? was trying to do a similar thing but the answers don't really help.

Any ideas on how I can keep the prefix DOMAIN\ in a TextBox?

like image 923
LukeHennerley Avatar asked Dec 07 '22 09:12

LukeHennerley


2 Answers

Using the KISS principle is indicated here. Trying to catch key presses just won't do anything when the user uses Ctrl+V or the context menu's Cut and Paste commands. Simply restore the text when anything happened that fudged the prefix:

    private const string textPrefix = @"DOMAIN\";

    private void textBox1_TextChanged(object sender, EventArgs e) {
        if (!textBox1.Text.StartsWith(textPrefix)) {
            textBox1.Text = textPrefix;
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }

And help the user avoid editing the prefix by accident:

    private void textBox1_Enter(object sender, EventArgs e) {
        textBox1.SelectionStart = textBox1.Text.Length;
    }
like image 100
Hans Passant Avatar answered Dec 28 '22 08:12

Hans Passant


Why not see in the event args of the textChanged what the value was before and the new value and if the Domain\ is not there in the new value, then keep the old one.

Or, why not just show the Domain\ as a label in front of the TextBox and just prepend it in code behind so that the final text is something like Domain\<username>.

like image 40
dutzu Avatar answered Dec 28 '22 08:12

dutzu