วันอังคารที่ 22 ตุลาคม พ.ศ. 2556

User Control เรียก Method จาก Parent Page ด้วย Reflection

สำหรับคนที่เขียนโปรแกรมด้วย User Control อาจประสบปัญหา เมื่อต้องการส่งข้อมูลจากเพจลูก (Child User Control) ไปยังเพจหลัก (Parent Page)  จะไม่สามารถทำได้ หรือใช้วิธีอื่นๆ แทน เช่น ส่ง Session แทน แต่มันมีวิธีอยู่นะ มาดูตัวอย่างเลยดีกว่า

Parent Page Method

public void DisplayMessage(string message)
{
   Response.Write(message);
}

Child User Control Method

protected void btnSend_Click(object sender, EventArgs e)
{
    this.Page.GetType().InvokeMember("DisplayMessage"/*ชื่อ Method ที่เพจหลัก*/, System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text/*Object ที่ต้องการส่งกลับไป*/ });
}

Credit: ASPSnippets