On my surveys.aspx page I have 5 user controls (containing different types of questions i.e. yes/no, multiple choice, open answer) that are dynamically loaded depending upon a formview. I have no problem loading these controls. The problem arises when I try to notify the aspx page that an event was triggered on the user control. (I need the parent page to recognize when an answer on one of the user controls has changed so it can update the database.) I can't for the life of me figure out how to pass the selection changed event to the parent page. Please help me.
Here is the code-behind of one of my user controls, followed by the applicable code of my parent page.
DQYesNo.ascx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class DQYesNo : System.Web.UI.UserControl
{
public delegate string AnswerSelectedEventHandler(string answer);
public event AnswerSelectedEventHandler AnswerSelectedComplete;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Check if event is null
if (AnswerSelectedComplete != null)
AnswerSelectedComplete(string.Empty);
RadioButtonList RadioButtonList1 = FindControl("RadioButtonList1") as RadioButtonList;
string answerNew = RadioButtonList1.SelectedValue;
}
}
surveys.aspx:
...
public void FormView1_DataBound(object sender, EventArgs e)
{
HiddenField itemID = FormView1.FindControl("itemID") as HiddenField;
string item = itemID.Value;
string answer = CheckRecords2();
HiddenField itemType = FormView1.FindControl("itemType") as HiddenField;
string txt = itemType.Value;
switch (txt)
{
case "yes/no":
Control DQYesNoUserControl = LoadControl("DQYesNo.ascx");
((HiddenField)DQYesNoUserControl.FindControl("HFitemID")).Value = item;
((HiddenField)DQYesNoUserControl.FindControl("HFanswer")).Value = answer;
if (answer == "No")
((RadioButtonList)DQYesNoUserControl.FindControl("RadioButtonList1")).Items[1].Selected = true;
else
((RadioButtonList)DQYesNoUserControl.FindControl("RadioButtonList1")).Items[0].Selected = true;
PlaceHolder Answers = FormView1.FindControl("PlaceHolder1") as PlaceHolder;
Answers.Controls.Add(DQYesNoUserControl);
DQYesNoUserControl.AnswerSelectedComplete += new DQYesNoUserControl.AnswerSelectedEventHandler(FormView1_AnswerSelectedComplete);
break;
...
}
}
...
//CUSTOM EVENT THAT BUBBLES FROM USER CONTROLS.
protected void FormView1_AnswerSelectedComplete(string answer)
{
//ASSIGN USER CONTROL ANSWER SELECTED TO HIDDEN FIELD.
HiddenField HFanswerNew = FormView1.FindControl("HFanswerNew") as HiddenField;
HFanswerNew.Value = answer;
}