窗体传值,一般用得多的方法有两个
一、属性构造函数
二、使用事件委托
属性构造函数例子:
<1> 创建两个窗体,Form1,Form2
<2>Form1窗体下按钮事件,弹出Form2,
Private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
F2.Show();
}
<3>Form窗体下,按钮事件,改变Form1窗体的背景颜色。
<4>在Form2,加一个带参数的构造函数:
public Form1 f1;
public Form2(From1 f):this()
{
f1 = f;
}
按钮事件:
f1.BackColor = Color.FromArgb(int red, int green,int blue);
具体代码如下:
Form1窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _01窗体传值
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.Show();
}
}
}
Form2窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _01窗体传值
{
public partial class Form2 : Form
{
Random r = new Random();
public Form1 f1;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 f):this()
{
f1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
f1.BackColor = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256));
}
}
}
第二种传值方式:使用事件委托
<1>新建两个窗体Form1, Form2
<2>定义一个委托类
<3>在Form2中声明一个委托事件变量
<4>在Form2按钮中调用委托事件
Form1窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _02事件委托实现窗体传值
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.chang += c => this.BackColor = c;
f2.Show();
}
}
}
Form2窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _02事件委托实现窗体传值
{
public partial class Form2 : Form
{
public event ChangeColorDelegate chang;
public Form2()
{
InitializeComponent();
}
Random r = new Random();
private void button1_Click(object sender, EventArgs e)
{
if (chang != null)
{
chang(Color.FromArgb(r.Next(256), r.Next(256), r.Next(256)));
}
}
}
}