Select text in front of the current text using Textbox

Asked

Viewed 90 times

2

I need that when a person type a word, automatically fills in front of the Textbox.

This is the DEFAULT text For Example:

  • sdfdsfasfColor this text in Textboxsdfdsassdf

When I fill a piece of the above text in the Textbox,

  • Lap(...)

The final result will have to look like this in the same Textbox that I type:

  • inserir a descrição da imagem aqui

Blue can only disappear when the word is not equal to the standard, or is higher.

I created a code for this, but at the time of typing, the selected text does not follow the word sequence of the standard text.

  private void TextBox1_TextChanged(object sender, EventArgs e)
  {
        int first = this.textBox1.TextLength;
        string padrao = "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi";
        string textIndex = padrao.Remove(0, padrao.IndexOf(this.textBox1.Text, 0) + this.textBox1.TextLength);            
        this.textBox1.Text = this.textBox1.Text.Insert(this.textBox1.Text.Length, textIndex);
        this.textBox1.Select(first, this.textBox1.Text.Length);
  }

My goal is just to select the default text while typing and put in front of the current text.

1 answer

2


The textbox has an auto complete mode, which differs from what it prefixes is that it only takes the start string.

public Form1()
{
    InitializeComponent();

    this.textBox1.AutoCompleteMode = AutoCompleteMode.Append;
    this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

    AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection
    {
        "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi"
    };

    textBox1.AutoCompleteCustomSource = stringCollection;
}

I made an example to get the string in the middle, I used a variable string calling for typed in class scope to save what was typed, has some flaws, need to remove characters in case of delete/Backspace, know where to remove, select multiple characters and delete etc....

string typed = "";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    string padrao = "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi";

    e.Handled = true;

    // TODO:: tratamento de delete, backspace, escape etc

    typed += ((char)e.KeyChar).ToString();

    this.textBox1.Text = typed;

    int indexOf = padrao.IndexOf(typed, StringComparison.OrdinalIgnoreCase);
    if (indexOf >= 0)
    {
        this.textBox1.Text += padrao.Substring(indexOf + typed.Length);
    }

     this.textBox1.SelectionStart = typed.Length;
     this.textBox1.SelectionLength = this.textBox1.Text.Length - typed.Length;

}
  • Excellent! I’ve been trying this for days and nothing...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.