【C#】winform跨窗体传值
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
方式一:使用变量传值 使用静态变量传值,可实现双向传值,但静态变量在类加载的时候分配内存,存储于方法区,一般不会被销毁,在系统不够内存情况下会自动回收静态内存,这样就会引起访问全局静态错误。
子窗体frmChild中代码 private void frmChild_Load(object sender, EventArgs e) { this.txtname.Text= frmMain.name.Trim(); //赋值 frmMain.name= "李四"; } 使用公共变量,只可实现单向传值。 public partial class frmMain : Form { //声明name为公共变量,并赋值 public string name= "张三"; //单击‘行为’按钮的时候会给窗体传值 private void btnChild_Click(object sender, EventArgs e) { frmChild f= new frmChild(); //变量传值 ,注意顺序写在ShowDialog()方法之前 f.stationID = this.name; f.ShowDialog(); } } 子窗体frmChild中代码 public partial class frmChild: Form { //定义公共属性 public string stationID = ""; } 方式二:使用委托传值 窗体设计如下: public partial class frmChild : Form { //1、声明一个委托 public delegate void setTextValue(string txt); //2、声明一个委托类型的事件 public event setTextValue setFormTextValue; public frmChild() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { setFormTextValue(textBox1.Text); } } 父窗体代码如下: public partial class frmFather : Form { public frmFather() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { frmChild c = new frmChild(); c.setFormTextValue += setLable; c.Show(); } public void setLable(string txt) { this.label1.Text = txt; } } 输入字符,点击发送按钮,运行结果如下: 思考一下,如果通过委托实现父窗体向子窗体传值? 该文章在 2023/5/15 22:00:50 编辑过 |
关键字查询
相关文章
|