WinForm窗体之间的传值

来源:互联网 发布:网络视频编辑 编辑:程序博客网 时间:2024/04/28 17:52
 

写一个类,就几行代码而已:

using System;
using System.Collections.Generic;
using System.Text;

namespace chuanzhi
{
    public sealed class Setting
    {
        private static volatile Setting instance;
        private static object syncRoot = new Object();

        private Setting() { }
        public static Setting Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Setting();
                    }
                }
                return instance;
            }
        }
    

        public string UserID;
             
    }
}


窗体1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace chuanzhi
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        Setting m_set = Setting.Instance;

        private void btnGo_Click(object sender, EventArgs e)
        {
            string UserID = this.txtUserID.Text.Trim();
            m_set.UserID = UserID;//这里是关键
            FrmNew f = new FrmNew();
            f.Show();
        }
    }
}


窗体2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace chuanzhi
{
    public partial class FrmNew : Form
    {
        public FrmNew()
        {
            InitializeComponent();
        }

        Setting m_set = Setting.Instance;
        private void FrmNew_Load(object sender, EventArgs e)
        {
            this.txtUserID.Text = m_set.UserID;//这里是赋值,关键所在
        }
    }
}

不管需要传多少值,只需要灵活的在这个类里面增加一个变量即可。

原创粉丝点击