zoukankan      html  css  js  c++  java
  • .Net子窗体给父窗体传值的几种方法

    其实方法有很多种,这里只介绍3种,大家如有更好的方法可互相学习学习。

    1.子父窗体Owner设定法:

    Form1:

    void Button_fm1_Click(object sender, EventArgs e)

    {

         Form2 fm2 = new Form2();

         fm2.Owner = this;   //将Form2的Owner指针指向Form1

         fm2.ShowDialog();

    }

    Form2:

    void Button_fm2_Click(object sender, EventArgs e)

    {

          Form1 fm1 = (Form1)this.Owner;  //将Form2的父窗体指针赋值给fm1

         fm1.Form1PublicTextBox.Text = this.TextBox.Text; //使用父窗体指针给父窗体中的TextBox赋值。(这里需设定父窗体中的TextBox的Modifier为Public)

          this.Close();

    }

    2. 提供TextBox属性方法

    Form2:

    namespace 子窗体传值父窗体

    {

      public Form1 fm1;

       ……

      

    void Button_fm2_Click(object sender, EventArgs e)

      {

        fm1.TextBox1.Text = this.TextBox1.Text;

        this.Close();

      }

    }

    Form1:

    void Button_fm1_Click(object sender, EventArgs e)

    {

         Form2 fm2 = new Form2();

         fm2.fm1= this;   //将fm1传值给fm2的fm1成员变量

         fm2.ShowDialog();

    }

    //提供Form1的一个公有属性指向TextBox1

    public TextBox Form1PublicTextBox
            {
                get 
                {
                    return this.TextBox1;
                }
            }

    3.委托实现方法

    新建一个委托:

         public delegate void UpdateTxtBoxDelegate(string txt);

    Form1:

    3.1 新增一个UpdateTextBox的方法:

      void UpdateTextBox(string txt)
            {
                this.textBox1.Text = txt;
            }

    3.2 

    void Button_fm1_Click(object sender, EventArgs e)

    {

         Form2 fm2 = new Form2(this.TextBox1.Text,UpdateTextBox);//将UpdateTextBox方法作为参数传给Form2

         fm2.ShowDialog();

    }

    Form2:

    public FormB(string userInput,UpdateTxtBoxDelegate uptxbdelegate):this()
            {
                this.textBox1.Text = userInput;
                
                _updatetxtbDel = uptxbdelegate;
            }

    private  UpdateTxtBoxDelegate _updatetxtbDel; //声明一个委托对象

    void Button_fm2_Click(object sender, EventArgs e)

      {

             _updatetxtbDel(this.textBox1.Text);

      }


    Impossible = I'm possible
    Don't be the same, be better. Just do it.
    You'll be there.
  • 相关阅读:
    MyEclipse 9.0 M1 安装 jad 反编译插件
    WPF(二)路由事件5.鼠标拖放
    WPF(二)路由事件2.挂起的事件
    DynamicDataDisplay 不压缩横坐标和图例的修改
    WPF(二)路由事件1.冒泡路由事件
    WPF(二)路由事件3.附加事件
    WPF(三)控件1.概述
    WPF(三)控件2.背景画刷和前景画刷
    WPF(二)路由事件4.隧道路由事件
    WPF(三)控件3.字体
  • 原文地址:https://www.cnblogs.com/gavin-king/p/4167856.html
Copyright © 2011-2022 走看看