Share via


How to: Use Button Controls

Buttons enable users to interact with your program. For example, many dialog boxes have an OK button and a Cancel button. Users can click the OK button to submit the information entered in the dialog box. Alternatively, they can click Cancel to close the dialog box without submitting any data.

You can set properties of a button to change its appearance. For example, you can set the Text property to display specific text on a button, or set the ForeColor property to change the color of the text. For more information, see How to: Create a Non-Rectangular Button.

Controls have events that are raised whenever a user performs a specific action on the control. You can create event handlers that determine how the program should respond to the event. All controls have a default event handler, and for a button, it is the Click event. The code that you write in the Click event handler of the button runs whenever the user clicks the button.

To use buttons in a program

  1. On the File menu, click NewProject.

  2. In the New Project dialog box, in the Templates pane, click Windows Forms Application.

  3. In the Name box, type ButtonExample, and then click OK.

    A new Windows Forms project opens.

  4. From the Toolbox, drag a Button onto the form.

  5. In the Properties window, change the Text property to read: Display Date and then press ENTER.

  6. In the Properties window, click the drop-down arrow to the right of the ForeColor property, and then click the Custom tab of the dialog box that opens.

  7. Click the red box to apply red font to the text of the button.

  8. In the form, double-click the button to open the Code Editor.

    The Code Editor opens in the middle of a method named button1_Click. This is the Click event handler. The code you write here will execute when the button is clicked.

  9. In the button1_Click event handler, type the following line of code.

    MessageBox.Show("Today is " +
        DateTime.Today.ToLongDateString());
    
  10. Press F5 to run your program.

  11. The program starts and the form appears. When you click the Button, a message box displays today's date.

See Also

Tasks

How to: Call a Button's Click Event Programmatically

Concepts

Designing a User Interface in Visual C#

Other Resources

Button Controls

Visual C# Guided Tour