日期:2014-05-17  浏览次数:20861 次

C#委托传值举例,在线等.....
请教用委托方式传值,要求双向的!
form1 中有textbox1和button1
单击button打开form2,在form2中有button2和textbox2
打开form2时要将textbox1中的值传到textbox2中,单击form2中的button2将textbox2中的值传到form1中的textbox1
如何用委托方法做?其他的方法已经会,不要在举例!

------解决方案--------------------
http://www.cnblogs.com/yagebuqq/archive/2008/05/29/1209760.html
------解决方案--------------------
public delegate void SetValueEventHandler(object sender,string value);

public class Form1()
{
......
private Form2 frm = null;
public event SetValueEventHandler SetValue;
......
private void button1_Click(object sender, EventArgs e)
{
if(frm==null)
{
frm = new Form2();
this.SetValue += new SetValueEventHandler(frm.SetValues);
}
if(this.SetValue != null)
{
SetValue(this, textBox1.Text);
}
frm.ShowDialog(); 
}
public void SetValues(object sender,string value)
{
this.textBox1.Text = value;
}

public class Form2()
{
......
private Form1 frm = null;
public event SetValueEventHandler SetValue;
......
public void SetValues(object sender,string value)
{
this.frm = (Form1)sender;
this.textBox2.Text = value;
}
private void button2_Click(object sender, EventArgs e)
{
if(frm != null)
{
if(this.SetValue != null)
{
this.SetValue += new SetValueEventHandler(frm.SetValues);
}
}
if(this.SetValue != null)
{
this.Close();
SetValue(this, textBox1.Text);
}
}
}

------解决方案--------------------

/// <summary>
/// 处理委托
/// </summary>
public delegate string CommandEventHandler2(); 
public partial class Form1 : Form
{
/// <summary>
/// 设置委托
/// </summary>
public CommandEventHandler2 command11 = null;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.command22 = new CommandEventHandler2(GetString);
form2.Show();
}

private void Form1_Load(object sender, EventArgs e)
{
DoCommand();

}
private string GetString()
{
return this.textBox1.Text;
}
private void DoCommand()
{
if (command11 != null)
{
this.textBox1.Text = command11();
}
}
}