窗体间的传值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了窗体间的传值相关的知识,希望对你有一定的参考价值。
1:通过属性传值
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
int a, b, sum;
if (int.TryParse(this.textBox1.Text, out a) && int.TryParse(textBox2.Text, out b))//关于TryParse的使用方法,见补充知识。
{
sum = a + b;
frm2.STR = sum.ToString();
frm2.ShowDialog();
}
else
{
frm2.STR = "输入的为非数字型字符串";
frm2.ShowDialog();
}
}
}
============
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string str;//定义的私有变量
public string STR//为窗体Form2定义的属性
{
get //读
{
return str;
}
set//写
{
str = value;
}
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = str;
}
}
2:通过构造函数传值
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(111, 222);
f2.ShowDialog();
}
}
Form2:
public partial class Form2 : Form
{
string str1, str2;
public Form2()
{
InitializeComponent();
}
public Form2(int t1, int t2)
{
InitializeComponent();//一定要加上
str1 = this.textBox1.Text;
str2 = this.textBox2.Text;
int a, b, sum;
if (int.TryParse(str1, out a) && int.TryParse(str2, out b))
{
sum = a + b;
}
else
{
MessageBox.Show("类型不正确");
}
}
}
3:通过静态变量双向传值
Form1:
private void button1_Click(object sender, EventArgs e)
{
App.value = "234567";
Form2 f2 = new Form2();
f2.Show();
}
Form2:
private void Form2_Load(object sender, EventArgs e)
{
this.textBox1.Text = App.value;
}
App类:
public class App
{
public static string value;
}
以上是关于窗体间的传值的主要内容,如果未能解决你的问题,请参考以下文章