C# Focus TextBox on Form Load

3 Comments »

When showing a form that contains a TextBox, it’s common courtesy to focus the TextBox so that the user can begin typing immediately.

To focus a TextBox when a Windows Form first loads, simply set the TabIndex for the TextBox to zero (or the lowest TabIndex for any Control on the Form).

When a Form is displayed, it automatically focuses the Control with the lowest TabIndex.  Note that if your TextBox is pre-initialized with some text, then the entire Text will be selected, as shown below:

Entire text is selected

Read the rest of this entry »

C# Read Text File Line-by-Line

36 Comments »

Here is the code to read a text file from disk one line at a time into a string.  This code ensures the file exists and properly closes the file if an exception occurs.

Read the rest of this entry »