C# 델리게이트
1. 폼간 데이터 전달(Form2신규 생성)
- Form1의 버튼을 누를때마다 Form2가 신규로 생성되며, From2의 textBox2에 Form1의 textBox1의 데이터가 써진다.
- Form2의 버튼을 누를때마다 Form1의 TextBox2에 데이터가 써진다.
// Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(); // 버튼을 누를때마다 폼을 생성한다.
frm2.Show();
frm2.WriteTextEvent += new Form2.TextEventHandler(frm2_WriteTextEvent); // 델리게이트를 통한 이벤트 등록
frm2.received2(textBox1.Text); //Form2로 데이터 전달
}
void frm2_WriteTextEvent(string text)
{
this.textBox2.Text = text;
}
}
//Form2
public partial class Form2 : Form
{
public delegate void TextEventHandler(string text);
public event TextEventHandler WriteTextEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WriteTextEvent(textBox1.Text); // 등록된 이벤트를 통하여 Form1으로 데이터 전달
}
public void received2(string str)
{
this.textBox2.Text = str;
textBox2.Invalidate();
}
}
2. 폼간 데이터 전달(Form2 1회 생성하여 상호간 데이터 전달)
- Form1의 버튼을 누를때마다 From2의 textBox2에 Form1의 textBox1의 데이터가 써진다.
- Form2의 버튼을 누를때마다 Form1의 TextBox2에 Form2의 textBox1의 데이터가 써진다.
// Form1
// Form1이 생성될때 Form2를 활성화해서 이후 이를 사용하여 데이터를 전달한다. Form2부분은 변화가 없다.
public partial class Form1 : Form
{
Form2 frm2 = new Form2(); // Form1 생성시 Form2 등록
public Form1()
{
InitializeComponent();
frm2.Show(); // Form2 Show
frm2.WriteTextEvent +=new Form2.TextEventHandler(frm2_WriteTextEvent); // 생성 당시 이벤트 등록
}
private void button1_Click(object sender, EventArgs e)
{
frm2.received2(textBox1.Text);
}
void frm2_WriteTextEvent(string text)
{
this.textBox2.Text = text;
}
}