Brandon Stout
Brandon Stout

Reputation: 359

How to replace characters in a text box as a user is typing in it? (in c#)

Ok, what I have going on is a textbox that has been filled with some text depending on what was selected from a listbox.

say the textbox looks like this:

blah blah ??? as?f

what I need to figure out how to do is whenever the user clicks in the textbox and deletes a "?" character, I would like to replace that character with an * and then whenever they try to delete the * it will be replaced by a "?" , so that the end result will look something like

blah blah **? as*f

if they deleted all but one "?".

No matter how long I have searched online I cannot seem to find anything similar.. the closest thing I have found is this question - Determine when and which character is added or deleted in a Text Box

But that doesnt really help for what I am trying to do.. if anyone has a good idea on where to start looking or even how to do it I would be very greatfull!

thanks in advance!

EDIT: Yes, this is for a Windows Form application, sorry i forgot to specify that. O.o

Upvotes: 4

Views: 7841

Answers (2)

Dmitry Shkuropatsky
Dmitry Shkuropatsky

Reputation: 3965

You can handle KeyDown event and bypass default handling. The event handler can look like the following:

public void OnKeyDown(Object sender, KeyEventArgs e)
{
   char[] text = textBox.Text.ToCharArray();
   int pos = textBox.SelectionStart;

   switch (e.KeyCode)
   {
       case Keys.Back: if (pos == 0) return; pos --; break;
       case Keys.Delete: if (pos == text.Length) return; break;
       default: return;
   }

   switch (text[pos])
   {
       case '?': text[pos] = '*'; break;
       case '*': text[pos] = '?'; break;
       default: return;
   }
   textBox.Text = new String(text);
   e.Handled = true;
}

You may also want to add checks for modifier keys, adjust cursor position, and implement custom behavior when text is selected, if needed.

Upvotes: 4

Milan Halada
Milan Halada

Reputation: 1934

Store textbox.Text in some string, after each key press (textbox.KeyPress) by comparing saved string with text inside textbox, find out if '?' was deleted, if it was insert '*' into textbox text on the right place.

//get indexes of all '?'
list<int> charlist = new list<int>();
string buff = textbox.Text;
for(int c = 0; c< buff.length, c++)
{
    if (buff[c] == '?')
    {
        charlist.add(c)
    }
}
//inside keypress event
foreach(int c in charlist)
{
    if (textbox.Text[c] != '?')
    {
        textbox.Text = textbox.Text.Insert(c, "*");
    }
}

Upvotes: 2

Related Questions