Как динамически добавлять радиокнопки, текстовые поля и кнопки в таблицу по коду? - PullRequest
1 голос
/ 20 октября 2010

Я пытаюсь динамически создать таблицу с радиокнопками, текстовыми полями и кнопками в каждой строке однозначно в зависимости от вопроса слева от TableRow с двумя TableCells.

Пока я смог добавить вопросы слева от Таблицы. Теперь мне трудно заполнить правую часть.

Может ли кто-нибудь мне помочь?

У меня есть следующий код:

private void DesignQuestionnaire(string[] questionList, Label question, RadioButtonList answerChoices, RadioButton choices, TextBox textAnswer, Button save, Button cancel)
    {
        Table formTable = new Table();
        TableRow formRow;
        TableCell formCell;

        for (int row = 0; row < questionList.Length; row++ )
        {
            formRow = new TableRow();
            formTable.Rows.Add(formRow);

            for (int col = 0; col < 2; col++ )
            {
                formCell = new TableCell();
                //formCell.Attributes.CssStyle.Add("border", "solid");
                if (col == 1)
                {
                    formCell.ID = "A" + row.ToString();
                    formCell.Controls.Add(choices);
                }
                else
                {
                    formCell.ID = "Q" + row.ToString();
                    formCell.Text = questionList.GetValue(row).ToString();
                }
                formRow.Cells.Add(formCell);
            }
        }
        Controls.Add(formTable);
    }

1 Ответ

0 голосов
/ 20 октября 2010

Обычно я справляюсь с подобной ситуацией, используя Repeater Control.

В aspx у вас будет что-то вроде этого:

<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="R1_ItemDataBound">
<HeaderTemplate>
<table>
</HeaderTemplate>

<ItemTemplate>
<tr>
    <td>
        <asp:Literal id="litQuestion" runat="server">
    </td>
    <td>
        <asp:PlaceHolder id="phRow" runat=server"/>
    </td>
<td>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

В коде позади вы должны иметь:

При загрузке страницы, только если это не PostBack

myRepeater.DataSource = myQuestions; // myQuestions would be a list of questions, for instance
myRepeater.DataBind();

А позже

void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {

          // This event is raised for the header, the footer, separators, and items.

          // Execute the following logic for Items and Alternating Items.
          if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
             string question = (string)e.Item.DataItem;
             Literal litQuestion = (Literal) e.Item.FindControl("litQuestion");
             litQuestion.Text = question;

             PlaceHolder phRow = (PlaceHolder) e.Item.FindControl("phRow");

             if (question.StartsWith("something")){
                 phRow.Controls.Add(new RadioButton("blabla"));
             }

             if (((Evaluation)e.Item.DataItem).Rating == "Good") {
                ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>";
             }
          }
       }   

Обратите внимание на OnItemDataBound в aspx: это означает, что R1_ItemDataBound будет вызываться для каждого элемента в вашем списке вопросов.

...