Reputation: 1319
I need to create dynamic radio buttons in my page, and then access their values in postback
I create the buttons using the following code:
foreach (Answer answer in question.Answers)
{
RadioButton radioButton = new RadioButton();
radioButton.Text = answer.Text;
radioButton.GroupName = question.Id.ToString();
radioButton.ID = question.Id + "_" + answer.Id;
TableRow answerRow = new TableRow();
TableCell answerCell = new TableCell();
TableCell emptyCell = new TableCell();
emptyCell.ColumnSpan = 2;
answerCell.Controls.Add(radioButton);
answerRow.Cells.Add(emptyCell);
answerRow.Cells.Add(answerCell);
table.Rows.Add(answerRow);
}
In the post back I try to access the radio buttons using their create ID:
foreach (Answer answer in question.Answers)
{
RadioButton currentAnswer = Page.FindControl(question.Id + "_" + answer.Id) as RadioButton;
if (currentAnswer != null) // Damn this null
{
if(currentAnswer.Checked)
{
answers[questionCounter] = answer;
}
}
else
{
allQuestionsAnswered = false;
}
}
But it seems that the find method is never finding the answer.
Please let me know when to use the above code. In the load method, in the preload, in the button click of the submit method.
It seems that I always get null and never find the control.
Upvotes: 0
Views: 2116
Reputation: 3891
Your control is not found because the FindControl method doesn't go down the control hierarchy, it only searches in the top level controls. You have to call it recursively for the controls in your page.
Upvotes: 1