纸上得来终觉浅,绝知此事要躬行。

 

WinForm窗体之间传值

在Winform编程中,如何在父窗体与子窗体间进行参数传递呢?下面是我采用的步骤总结,后面有源代码示例,供大家参考。

 

1 父窗体中声明一个静态的父窗体类型的临时对象

 

        public static frmFather frmFatherTemp;

2 父窗体构造函数中对该变量赋值

        public frmFather()
        {
            InitializeComponent();
            frmFatherTemp = this;
        }

3 把要传递的参数设置为父窗体的一个属性,并设置访问器。访问其的set方法中进行了参数与父窗体控件绑定的操作。

        private string testValue;
        
        public string TestValue
        {
            get 
            {
                return testValue;    
            }
            set 
            {
                this.testValue = value;
                this.txtFather.Text = value;
            }
        }

4 父窗体参数传递事件中对要传递的参数赋值,并打开子窗体。父窗体的工作到此结束。

            this.TestValue = this.txtFather.Text;//赋值操作
            frmSon frm = new frmSon();
            frm.ShowDialog();

//以下为子窗体操作

5 子窗体构造函数中设置传递参数与子窗体控件的绑定操作

        public frmSon()
        {
            InitializeComponent();
            this.txtSon.Text = frmFather.frmFatherTemp.TestValue;//获取父窗体传过来的值
        }

6 子窗体回传事件中,对父窗体的临时对象的该参数属性赋值

        public frmSon()
        {
            InitializeComponent();
            //this.txtSon.Text = frmFather.frmFatherTemp.TestValue;

            //frmFather.frmFatherTemp.TestValue="要回传的值";
        }

至此,窗体之间的单向传值就完成了(已验证),至于再回传一个值,还没有验证是否可行。

posted on 2010-11-25 11:43  JRoger  阅读(814)  评论(0编辑  收藏  举报

导航