如何通过代码在表中动态添加单选按钮,文本框和按钮?

时间:2010-10-20 06:26:56

标签: c# radio-button tablerow tablecell

我正在尝试动态创建一个表格,每个行上都有单独的单选按钮,文本框和按钮,具体取决于具有两个TableCell的TableRow左侧的问题。

到目前为止,我能够将问题添加到TableRow的左侧。现在,我很难填写它的右侧。

有人可以帮助我吗?

我在下面有以下代码:

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 :(得分:0)

我通常使用Repeater控制来处理这种情况。

在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>";
             }
          }
       }   

请注意aspx中的OnItemDataBound:这意味着系统会为您问题列表中的每个项目调用R1_ItemDataBound