以编程方式生成WebControl

时间:2009-05-15 18:00:38

标签: asp.net

我有一个页面,根据前一页的输入,列出从数据库中提取的不同数量的不同问题。我似乎无法在线找到这样的示例:对于显示的每个问题,我需要以编程方式生成DropDownList,以便用户可以为每个问题选择是或否。希望有人在这里可以给我一些指导方向。

3 个答案:

答案 0 :(得分:3)

可能你最好的选择是使用Repeater控件和一个模板,该模板只包含带有静态列表项的下拉列表。像这样:

<asp:Repeater runat="server" id="questionRepeater">
<HeaderTemplate>
  //some html
</HeaderTemplate>
<ItemTemplate>
<div align=center>
<asp:Label runat="server"><%# DataBinder.Eval(Container.DataItem,"questionColumn")%></asp:Label>
<asp:DropDownList runat="server">
   <asp:ListItem Text="Yes" Value="1" />
   <asp:ListItem text="No" Value="0" />
</asp:DropDownList>
</ItemTemplate> 
</asp:Repeater>

然后在您的代码中,您可以执行查询并将结果绑定到转发器。

private void Page_Load(object sender, System.EventArgs e)  
{  
   if (!IsPostBack)
   {
    SqlConnection db = new SqlConnection("Server=server;UID=uid;PWD=password;Database=whatever");  
   string sSQL = "Select questionColumn from Questions";
   SqlCommand cmd = new SqlCommand(sSQL, conDotNet);   
   db.Open();  
   SqlDataReader dtrCat = cmd.ExecuteReader();  
   questionRepeater.DataSource = dtrCat;  
  questionRepeater.DataBind();  
  }
}

答案 1 :(得分:2)

这是假的,但可能有帮助...

//essentially, run through loop of questions and for each
//add the question and yes/no stuff..
///PlaceHolder is a ContentPlaceholder Control within the .aspx page.
foreach(inputtype input in this.inputs)
{
    Label lbl = new Label();
    lbl.Text = input.Question;

    DropDownList ddl = new DropDownList();
    ddl.ID = input.QuestionID;
    ddl.DataSource = YesNoDataTable;
    ddl.DataBind();

    this.PlaceHolder.Controls.Add(lbl);
    this.PlaceHolder.Controls.Add(ddl);
}

答案 2 :(得分:0)

Dim tDropDownList As DropDownList = Nothing
Dim tQuestion As String = String.Empty

For Each tQuestion In tQuestions
    tDropDownList = New DropDownList
    tDropDownList.Name = "someName here"
    tDropDownList.Items.Add("Yes")
    tDropDownList.Items.Add("No")
    Page.Constrols.Add(tDropDownList)
Next