首先 有两个form窗体 Form1,Form2和一个usercontrol usercontrol1
1、在Form1窗体中有一个 splitContainer1容器控件 splitContainer1.panle1中有一个button button事件:
private void button1_Click(object sender, EventArgs e)
{
UserControl1 uc = new UserControl1();
this.splitContainer1.Panel2.Controls.Add(uc);
}
2、usercontrol中有一个lable1和一个button1控件 button事件:
private void button1_Click(object sender, EventArgs e)
{
Form2 fm = new Form2();
fm.ShowDialog();
}
3、在Form2窗体中有一个button控件 button事件来对usercontrol中的lable1的text赋值
这时需要委托
具体代码:
Form1 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UserControl1 uc = new UserControl1();
this.splitContainer1.Panel2.Controls.Add(uc);
}
}
}
usercontrol代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public void setvalue()
{
this.label1.Text ="2";
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fm = new Form2();
fm.btnokclick += new Form2.BtnClick(fm_btnokclick);
fm.ShowDialog();
}
void fm_btnokclick()
{
setvalue();
}
}
}
Form2 代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form2 : Form
{
//定义一个委托
public delegate void BtnClick();
//声明一个委托事件
public event BtnClick btnokclick;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (btnokclick != null)
{
btnokclick();
}
}
}
}
这样就可以对usercontrol中的控件进行刷新了 hoho~