开发者

ASP.net 2.0 dynamic Radio Button

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜