码迷,mamicode.com
首页 > Windows程序 > 详细

窗体间的传值

时间:2016-03-10 20:22:46      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

 

窗体间的传值

标签:

原文地址:http://www.cnblogs.com/haunggl-2016/p/5263089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!