Tuesday, May 3, 2016

Create a windows form to add two numbers and display the result in a TextBox.


1. Open Visual studio 2013
2. On the menu bar, choose File, New, and Project
3. Choose Programming language as  Visual C# . In the templates list, choose the Windows Forms       
   application icon. 
4. set the name the project as ADDNUM and specify the address of your folder. (You can give other names as      required by you).
5. In the main window, design the form as shown below by dragging the tools from the toolbox present in the left side 
There are three textboxes present in the above diagram and these textboxes are named as txtnum1,txtnum2 and txtresult respectively. The name can be changed by clicking (Right-click) on the textbox and select properties. In the properties window, you can change the name, text , size and many other properties of the Textbox control.

Similarly, the diagram has three labels and one button. The labels are named as Number1, Number2 & Result respectively . The name of the button is set to Add.

Now, double click the Add button, and write the following code in the code area opened after double click. (in the button_click event).

private void add_Click(object sender, EventArgs e)
        {
           float number1 = float.Parse(txtnum1.Text);
           float number2 = float.Parse(txtnum2.Text);
           float res =number1+ numbe2;
           result.Text = res.ToString();
        }


Explanation:

Here, number1, number2 and res are declared as float variables. The first statement receives the text from the textbox "txtnum1" and converts it into floating point type using float.Parse, and stores the converted value in the variable number1. similarly for number2.
Now number1 and number2 are added and the result is stored in another variable res.

Finally, the value of the variable res, is converted into string using the statement res.ToString() before it is displayed in the textbox named txtresult.

After writing the code, save your project by pressing ctrl+s, and execute it. 

Enjoy coding...



No comments:

Post a Comment