[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make Ctrl+A select all of the text in a TextBox in C#

[Make Ctrl+A select all of the text in a TextBox in C#]

Often it's convenient for the user to be able to press Ctrl+A to select all of the text in the TextBox that has the focus. Strangely that's not the default behavior for the TextBox. Perhaps the TextBox doesn't handle Ctrl+A so the program can use Ctrl+A as an accelerator.

This example uses the following KeyPress event handler to select all of the text in a TextBox when the user presses Ctrl+A in it.

// On Ctrl+A, select all of the TextBox's text. private void CtrlA_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == Convert.ToChar(1)) { TextBox txt = sender as TextBox; txt.SelectAll(); e.Handled = true; } }

If the key pressed is Ctrl+A, the code converts the sender parameter into a TextBox and calls that control's SelectAll method to select its text. The code uses the sender parameter instead of a specific hard-wired TextBox so you can use the same event handler for any number of TextBox controls.

After selecting the text, the code sets the e.Handled parameter to true to indicate that the event has been handled and the program should not try to handle it further. If you don't do that, the event passes to the TextBox control's default event handler, which beeps when it sees Ctrl+A.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.