Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Auto Clearing Winform Textbox

Tags:

I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents.

The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome.

The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.

Edit: The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.

like image 286
Robin Robinson Avatar asked Aug 19 '08 12:08

Robin Robinson


2 Answers

Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.

TextBox1.Select(0, TextBox1.Text.Length);
like image 60
Greg Hurlman Avatar answered Oct 12 '22 09:10

Greg Hurlman


OK, are you sure that is wise? I am picturing two scenarios here:

  1. There is a default button on the form, which is "clicked" when enter is pushed".
  2. There is no default button, and you want the user to have to press enter, regardless.

Both of these raise the same questions:

  • Is there any validation that is taking place on the text?
  • Why not create a user control to encapsulate this logic?
  • If you know the enter button is being pushed and consumed fine, how are you having problems with TextBoxName.Text = string.Empty ?

Also, as a polite note, can you please try and break up your question a bit? One big block is a bit of a pain to read..

like image 22
Rob Cooper Avatar answered Oct 12 '22 09:10

Rob Cooper