ในตัวอย่างนี้ผมจะใช้ Delegate ในการรับและส่งค่าระหว่าง Form นะครับ
1. สร้าง form 2 form ขึ้นมา ใน form แรก ให้ลาก numericUpDown,Button มาวางใน form , ใน form 2 ลาก label มาวางเพื่อแสดงค่าของ numericupdown ที่ถูกส่งมาจาก form1
2.ใน form 1 คลิกที่ปุ่ม Button แล้วเขียนโค้ดดังนี้
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
SendDataToForm2 mydelegate = new SendDataToForm2(form2.GetData);
mydelegate(this.numericUpDown1.Value.ToString());
form2.Show();
}
***ให้ประกาศ Delegate ก่อนคลาสด้วยดังนี้
public delegate void SendDataToForm2(string txt);
3. ที่ Form2 เพิ่มเมธอดังนี้
public void GetData(string txt)
{
label1.Text = txt;
}
4. ผลลัพธ์ดังรูป

5. เมื่อกำหนดตัวเลขใน numericupdown แล้วคลิกทีปุ่ม Send ก็จะมี form 2 เกิดขึ้นมาดังรูป

ตัวอย่างโค้ดหมดใน Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public delegate void SendDataToForm2(string txt);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
SendDataToForm2 mydelegate = new SendDataToForm2(form2.GetData);
mydelegate(this.numericUpDown1.Value.ToString());
form2.Show();
}
}
}
ตัวอย่างโค้ดทั้งหมดใน Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
public void GetData(string txt)
{
label1.Text = txt;
}
}
}
[With great power comes great responsibility]