zoukankan      html  css  js  c++  java
  • 【转】C# 子窗体如何调用父窗体的方法

    网络上有几种方法,先总结如下:
    调用窗体(父):FormFather,被调用窗体(子):FormSub。

    方法1: 所有权法
           //FormFather:
           //需要有一个公共的刷新方法
           public void Refresh_Method()
           {
                   //...
           }
           //在调用FormSub时,要把FormSub的所有者设为FormFather
           FormSub f2 = new FormSub() ;
           f2.Owner = this;
           f2.ShowDialog() ;


           //FormSub:
           //在需要对其调用者(父)刷新时
           FormFather f1 ;
           f1 = (FormFather)this.Owner;
           f1.Refresh_Method() ;

     

    方法2:自身传递法
           //FormFather:
           //需要有一个公共的刷新方法
           public void Refresh_Method()
           {
                   //...
           }
           FormSub f2 = new FormSub() ;
           f2.ShowDialog(this) ;


           //FormSub:
           private FormFather p_f1;
           public FormSub(FormFather f1)
           {
                   InitializeComponent();
                   p_f1 = f1;
           }
           //刷新时
           p_f1.Refresh_Method() ;

     

    方法3:属性法
           //FormFather:
           //需要有一个公共的刷新方法
           public void Refresh_Method()
           {
                   //...
           }
           //调用时
           FormSub f2 = new FormSub() ;
           f2.P_F1 = this; //重点,赋值到子窗体对应属性
           f2.Show() ;

           //FormSub:
           private FormFather p_f1;
           public FormFather P_F1
           {
                   get{return p_f1;}
                   set{p_f1 = value;}
           }
           //刷新时
           p_f1.Refresh_Method() ;


    方法4:委托法
           //FormFather:
           //需要有一个公共的刷新方法
           public void Refresh_Method()
           {
                   //...
           }
           //调用时
           FormSub f2 = new FormSub() ;
           f2.ShowUpdate += new DisplayUpdate(Refresh_Method) ;
           f2.Show() ;


           //FormSub:
           //声明一个委托
           public delegate void DisplayUpdate();
           //声明事件
           public event DisplayUpdate ShowUpdate;
           //刷新时,放在需要执行刷新的事件里

           if(ShowUpdate!=null)   ShowUpdate();

     

           //子窗体提交后
           private void btnOK_Click(object sender, EventArgs e)
           {
                   this.DialogResult = DialogResult.OK;
                   this.Close();
           }

     

          //判断子窗体
           if(form.ShowDialog() == DialogResult.OK)
           {
                    刷新父窗体中的DataGRIDVIEW数据
           }

  • 相关阅读:
    js面向对象和PHP面相对象
    git
    css3动画、2D与3D效果
    渲染数据方式
    ajax
    面向对象
    Date 日期
    Math 数值对象
    What is CGLib and JDK动态代理
    IDEA中lock对象不提示newCondition();
  • 原文地址:https://www.cnblogs.com/netlyf/p/4436584.html
Copyright © 2011-2022 走看看