Share via


How to: Get a Value from Another Form

This topic describes how to retrieve a value from a text box on a Windows Form and display it in a text box on another form.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To get a value from another form

  1. On the File menu, point to New and then click Project.

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

    A new Windows Forms project opens.

  3. From the Toolbox, drag one TextBox and one Button control onto the form.

  4. In Solution Explorer, right-click the project, click Add, and then click New Item.

    In the Add New Item dialog box, in the Templates pane, click Windows Form, and then click Add.

    A new Windows Form (Form2) opens.

  5. From the Toolbox, drag one TextBox control onto the form.

  6. Change the Text property of the TextBox control to Sample text. The first form will read and display this property.

  7. Change the Modifiers property of the TextBox control from Private to Public to enable other forms to access this control.

  8. In Solution Explorer, right-click Form1.cs, and then click View Designer.

  9. In the form, double-click the button to create a Click event handler.

  10. Before the button1_Click event handler, add the following code to create an object that enables access to the components and properties of Form2:

    private Form2 otherForm = new Form2();
    
  11. In the button1_Click event handler, add the following code to get the value from the text box on Form2 and assign it to the text box on Form1:

    textBox1.Text = otherForm.textBox1.Text;
    
  12. Press F5 to run the program.

  13. The program starts and the form appears. When you click the button on Form1, the text from the text box on Form2 appears in the text box on Form1.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

Customizing, Displaying, and Printing Windows Forms

Visual C# Guided Tour

Change History

Date

History

Reason

September 2008

Revised code example and added step-by-step instructions.

Customer feedback.