需求:父窗体一TextBox点击后弹出子窗体,在子窗体中数值计算后返回结果给父窗体中的TextBox.
设计:
1、父窗体:一TextBox控件
2、子窗体:两个TextBox控件,分别用于接受两个数值;一个Combobox控件用于选中运算符,一Lable控件;一Button控件,取结果返回并关闭子窗体。
实现:
1、Program.cs
namespace CalculateForWhat
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
//Application.Run(new Form2());
}
}
}
2、Form1父窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CalculateForWhat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtbox_ReceiveVal_Click(object sender, EventArgs e)
{
Form2 f = new Form2(this);//注意将当前父窗体实例传递到Form2
f.Show();
}
}
}
3、Form2子窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace CalculateForWhat
{
public partial class Form2 : Form
{
Form1 _frm1;
public Form2(Form1 frm1)
{
InitializeComponent();
this.BindCombobox();
this._frm1 = frm1;//接受父窗体实例,这样就可用_frm1调用父窗体控件
}
private void BindCombobox()
{
//throw new Exception("The method or operation is not implemented.");
ArrayList al = new ArrayList();
al.Add("+");
al.Add("-");
al.Add("*");
al.Add("/");
this.comboBox1.DataSource = al;
}
private void btn_GetVal_Click(object sender, EventArgs e)
{
double val1, val2;
double finalVal;
try
{
val1 = Convert.ToDouble(this.textBox1.Text.Trim());
val2 = Convert.ToDouble(this.textBox2.Text.Trim());
}
catch
{
MessageBox.Show("请在文本框中输入数值!!", "出错啦", MessageBoxButtons.OK);
return;
}
string flag = this.comboBox1.SelectedValue.ToString();
switch (flag)
{
case "+":
finalVal = val1 + val2;
break;
case "-":
finalVal = val1 - val2;
break;
case "*":
finalVal = val1 * val2;
break;
case "/":
finalVal = val1 / val2;
break;
default: throw new Exception("错误的运算符!!");
break;
}
this._frm1.txtbox_ReceiveVal.Text = finalVal.ToString();//Success
this.Close();//关闭当前窗体
}
}
}
--------------------------------------------
END