How to replace characters in a text box when a user enters it? (in c #)

Well, what I'm doing is a text box that was filled with some text depending on what was selected from the list.

let's say the text box looks like this:

blah blah ??? as?f 

what do I need to figure out how to do this when the user clicks the text box and removes the "?" character, I would like to replace this character with *, and then whenever they try to delete *, it will be replaced by "?" so the end result will look something like

 blah blah **? as*f 

if they deleted all but one "?" .

No matter how much time I searched on the Internet, I can not find anything like it. The closest I found is the question - Determine when and which character is added or deleted in the text box

But that really doesn't help for what I'm trying to do. If anyone has a good idea about where to start looking or even how to do it, I would really like to!

early!

EDIT: Yes, this is for a Windows Form application, sorry, I forgot to specify this. Oo

+4
source share
2 answers

You can handle the KeyDown event and bypass the default processing. An event handler might look like this:

 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 can also add modifier key checks, adjust the cursor position and implement custom text selection behavior if necessary.

+4
source

Save textbox.Text in some line, after each keystroke (textbox.KeyPress), comparing the saved line with the text inside the text field, find out if there is a '?' was deleted if it was inserted '*' in the text text in 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, "*"); } } 
+2
source

Source: https://habr.com/ru/post/1398343/


All Articles