• winform 利用委托实现窗体传值


           父窗体:Form1    ,有个 textbox1.text ,有个button1

      子窗体:Form2  ,有个 textbox1.text ,有个button1

      修改Form1 的textbox1.text  ,点击Form1的 button1,弹出Form2,点击Form2 的button ,结果:Form2的 textbox1.text 的值为  Form1的textbox1.text ,修改下 Form1的textbox1.text ,再点Form2 的button  ,Form2的 textbox1.text 的值与Form1的 textbox1.text 保持一致

    首先在Form2中定义委托和事件:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace TestDelegate
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
    
            private void Form2_Load(object sender, EventArgs e)
            {
    
            }
    
            public delegate string TransfDelegate();   //委托的方法体必须返回值为string,无参数
    
            public event TransfDelegate TransfEvent;
    
            private void button1_Click(object sender, EventArgs e)
            {         
                textBox1.Text = TransfEvent();
            }    
    
           
          
        }
    }
    

      

      

    然后在Form1中进行调用:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace TestDelegate
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
           
            private void button1_Click(object sender, EventArgs e)
            {            
                Form2 frm = new Form2();
                //注册事件
                frm.TransfEvent += GetValueEvent;
                frm.Show();
            }
    
            string GetValueEvent()   
            {
                return textBox1.Text;
            }
        }
    }
    

      

      

  • 相关阅读:
    Delphi7 (第一天:类的编写)
    设计模式(二)Abstract Factory
    hdu 3335(最小路径覆盖)
    hdu 2236(最大匹配+枚举上下界)
    hdu 2819(二分匹配)
    hdu 3861(缩点+最小路径覆盖)
    hdu 2831(贪心)
    hdu 4296(贪心)
    hdu 2354(bfs求最短路)
    hdu 4313(类似于kruskal)
  • 原文地址:https://www.cnblogs.com/wdw31210/p/7592112.html
Copyright © 2020-2023  润新知