by Dr. Zhang
Examples: Adder, Temperature Converter and Vacation Planner
private void button1_Click(object sender, EventArgs e) { double sum; sum = Convert.ToDouble(textBox1.Text) + Convert.ToDouble(textBox2.Text); label1.Text = sum.ToString(); }
Example: Temperature Converter
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TemperatureConverterVS2012 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //Convert from Fahrenheit to Celsius private void button1_Click(object sender, EventArgs e) { double tempC = 0; double tempF = 0; tempF = Convert.ToDouble(textBox1.Text); tempC = 5.0 / 9.0 * (tempF - 32); textBox2.Text = tempC.ToString("0.00"); } //Convert from Celsius to Fahrenheit private void button2_Click(object sender, EventArgs e) { double tempC = 0; double tempF = 0; tempC = Convert.ToDouble(textBox2.Text); tempF = 9.0 / 5.0 * tempC + 32; textBox1.Text = tempF.ToString("0.00"); } private void textBox1_TextChanged(object sender, EventArgs e) { //button1_Click(sender, e); } private void textBox2_TextChanged(object sender, EventArgs e) { //button2_Click(sender, e); } } }
Example: Vacation Planner
In this example, more graphical controls are used, such as calendars, dropdown menus and radio buttons.
Tips of Form Design:
Code Behind in C#
public Form1() { InitializeComponent(); //Set the number of rooms to zero and the first city selected comboBox1.SelectedIndex = 0; radioButton1.Checked = true; } private void button1_Click(object sender, EventArgs e) { //Declarations of variables int rooms; int nights; double rate; double total; DateTime checkin; DateTime checkout; TimeSpan duration; //Get the number of rooms booked rooms = comboBox1.SelectedIndex; //Get arrival and departure dates checkin = monthCalendar1.SelectionStart; checkout = monthCalendar2.SelectionStart; //Calculate the number of days to stay in duration = checkout - checkin; nights = duration.Days; if (nights <= 0) MessageBox.Show("Departure date should be later than arrival date"); //Determine the room rates based on the cities if (radioButton1.Checked == true) rate = 200.0; else if (radioButton2.Checked == true) rate = 150.0; else rate = 250.0; //Calculate the total costs total = rate * rooms * nights; //Display the total costs in the text box label6.Text = "$" + total.ToString(); }