C# WinForm 窗体传值

方法集合

方法一:所有权法

效果

父窗体代码

           #region 方法1:所有权法     
           //在调用 ZiForm 时,要把Form2的所有者设为 FuForm    
           ZiForm f2 = new ZiForm();
           f2.Owner = this;//把Form2的所有者设为 FuForm    
           f2.ShowDialog();
           #endregion

子窗体代码

           //需要传的值
           var text = textBox1.Text;
           #region 方法1:所有权法 
           FuForm f1;
           f1 = (FuForm)this.Owner;
           f1.Refresh_Method(text);
           #endregion

方法二:自身传递法

效果

父窗体代码

            #region 方法2:自身传递法 
            ZiForm f2 = new ZiForm();
            f2.fuForm = this;
            f2.ShowDialog();
            #endregion

子窗体代码

           #region 方法2:自身传递法
           public FuForm fuForm;
           public ZiForm(FuForm f1)
           {
                  InitializeComponent();
                  fuForm = f1;
           }
           #endregion
           //调用
           #region 方法2:自身传递法
           fuForm.Refresh_Method(text);
           #endregion

方法三:属性法

效果

父窗体代码

            #region 方法3:属性法
            ZiForm f2 = new ZiForm();
            f2.FuForm1 = this;
            f2.ShowDialog();
            #endregion

子窗体代码

        #region 方法3:属性法  
        private FuForm _FuForm1;
        public FuForm FuForm1
        {
                get { return _FuForm1; }
                set { _FuForm1 = value; }
         }
        #endregion
        //调用
        #region 方法3:属性法     
        FuForm1.Refresh_Method(text);
        #endregion

方法四:委托法

效果

父窗体代码

            #region 方法4:委托法 
            ZiForm f2 = new ZiForm();
            f2.ShowUpdate += new DisplayUpdate(Refresh_Method);
            f2.ShowDialog();
            #endregion

子窗体代码

        #region 方法4:委托法 
        //声明一个委托    
        public delegate void displayupdate(string va);
        //声明事件    
        public event displayupdate showupdate;
        #endregion
        //调用
        #region 方法4:委托法 
        ShowUpdate(text);
        #endregion

方法五:消息法(此方法目前无实现传值,且会关闭当前子窗体)

效果

父窗体代码

        #region 方法5:消息法
        ZiForm f2 = new ZiForm();
        if (f2.ShowDialog(this) == DialogResult.OK)
        {
                Refresh_Method();
        }
        #endregion

子窗体代码

//调用
        #region 方法5:消息法
         this.DialogResult = System.Windows.Forms.DialogResult.OK;
        #endregion
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容