用构造函数在窗体之间传递数据类的相互调用实例

主窗体的程序

public partial class 主程序 : Form
    {
        public 主程序()
        {
            InitializeComponent();
        }

        //当点击显示对话框时
        private void button2_Click(object sender, EventArgs e)
        {
            
            //将自己传递给另一个类(对话框登录)的实例
            对话框登录 frm = new 对话框登录(this);
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.Cancel)
            {
                label1.Text = "取消登录";
            }
        }
        public void 显示对话框的数据(string 用户名, string 密码)
        {
            label1.Text = string.Format("您输入的用户名是:{0},密码是{1}.",用户名,密码);
        }
    }

对话框的程序,对用户输入的内容做了一些验证,通过后才会OK,不然只能取消

public partial class 对话框登录 : Form
    {
        public 对话框登录()
        {
            InitializeComponent();
        }

        private 主程序 调用者 = null;
        public 对话框登录(主程序 invoker)
            : this()//注意要加上这个,不然对话框上什么也没有
        {
            this.调用者 = invoker;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (textBox用户名.Text == "a" && textBox密码.Text == "123")
            {
               //使用传递进来的调用者的方法
                this.调用者.显示对话框的数据(textBox用户名.Text, textBox密码.Text);
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("用户或者密码错误");
            }
        }
    }
这样就实现了当在对话框中输入正确的内容,并点击确定后就会在其调用者主程序中显示出输入的用户名和密码
image
主程序中显示的内容:
image

使用构造函数来进行类之间的相互调用还是感觉有点晕人!

原文地址:https://www.cnblogs.com/angestudy/p/2007123.html