【问题标题】:How to create VB.NET controls dynamically based on dropdown values如何根据下拉值动态创建 VB.NET 控件
【发布时间】:2026-01-16 17:55:02
【问题描述】:

请提供任何有用的链接。

我需要在 VB.NET 中创建一个示例问题类型 Web 表单,它允许用户执行以下操作:

  1. 用户从下拉列表中选择控件类型(TextBox、RadioButton、ListBox 等)。
  2. 根据网络表单上的控件类型动态生成控件。
  3. 它将始终显示 TextBox(用户在其中写问题)和(生成的控件 - TextBox、RadioButton、ListBox 等)并将这些值保存到数据库中。

  4. 在 Web 表单上显示生成的示例问题。

谢谢。

【问题讨论】:

  • 这是什么意思:“用户编写问题,并将生成的问题保存到数据库中。” ?当您只知道用户想要一个 ListBox 时,您将如何填充 ListBox 之类的控件?
  • 我认为您将要构建两个不同的 UI。首先是创建一个 UI,允许您创建和管理问题和可能的答案。第二个是如何获取存储的数据并呈现一个表单供用户交互以回答问题。

标签: c# asp.net vb.net


【解决方案1】:

这样的东西应该可以工作(无需数据库交互;))。

aspx:

<asp:DropDownList runat="server" id="TypeDropDown" OnSelectedIndexChanged="OnTypeChanged">
  <asp:ListItem>TextBox</asp:ListItem>
  <asp:ListItem>RadioButton</asp:ListItem>
</asp:DropDownList>
<asp:Panel>
    Question: <asp:TextBox runat="server" ID="Question" /> <br />
    Answer: <asp:PlaceHolder runat="server" ID="Place" />
</asp:Panel>

代码隐藏:

protected override void OnInit(EventArgs eventArgs) {
  base.OnInit(eventArgs);
  CreateDynamicControl(); 
}

private void CreateDynamicControl() {
  Place.Controls.Clear();
  Place.Controls.Add(ControlFactory.Create(TypeDropDown.SelectedValue);
}

private void OnTypeChanged(object sender, EventArgs eventArgs) {
  CreateDynamicControl();
}

控制工厂:

static class ControlFactory {
  public static Control Create(string type) {
    if ("TextBox".Equals(type))
      return new TextBox();

    if ("RadioButton".Equals(type)) 
      return new RadioButtonList();
  }
}

【讨论】:

    【解决方案2】:

    我认为您正在寻找的是一种 DBMS 解决方案,您可以在其中将控件的类型保存在数据库中,而不是何时显示您正在查看的类型的页面并使用占位符来生成您需要的内容。 这是解释 DBMS 的*链接:http://en.wikipedia.org/wiki/Database_management_system

    【讨论】:

      【解决方案3】:

      我使用声明式语法和 DataBinding 做了类似的事情。

      抱歉,代码太长了,但只发布没有嵌套中继器的相关部分可能没有意义。我正在为上下文发布完整的嵌套中继器代码。

      在我的设置中,这是一个调查应用程序,带有 问题组(外部中继器),由一个或多个 问题(嵌套中继器)组成。

      其工作原理的相关部分在代码示例中的嵌套中继器中。我在标记中拥有所有可用的控件。但是每个的 .Visible 属性是根据 QuestionType 设置的。

          <asp:Repeater ID="Repeater1" runat="server">
              <ItemTemplate>
                  <div class="questiongroup">
                      <asp:HiddenField runat="server" ID="lblQuestionGroupId" Value='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "QuestionGroupId").ToString()) %>'>
                      </asp:HiddenField>
                      <asp:HiddenField runat="server" ID="hfSortOrder" Value='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "SortOrder").ToString()) %>'>
                      </asp:HiddenField>
                      <asp:HiddenField runat="server" ID="hdnPointsAwarded" Value='0'></asp:HiddenField>
                      <br />
                      <h3><asp:Label runat="server" ID="txtQuestionGroupName" MaxLength="50" Columns="50" Text='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "QuestionGroupName").ToString()) %>'></asp:Label>
                      </h3>
                      Score Section
                      <asp:CheckBox runat="server" ID="chkIsScoreSection" Enabled="false" TabIndex="-1"
                          Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "IsScoreSection")) %>' />
                      Minimum required correct answers:
                      <asp:Label runat="server" ID="lblMinimumForScore" MaxLength="3" Columns="3" Text='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "CommentsRequiredMinimumYesAnswers").ToString()) %>'></asp:Label>
                        Point Value <asp:Label ID="lblPossiblePoints" runat="server" Text='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "PossiblePoints").ToString()) %>' />
                                <br />
                      Group Instructions
                      <br />
                      <asp:Label runat="server" ID="lblGroupInstructions" TextMode="MultiLine" Columns="50" Rows="3"
                          Text='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "GroupInstructions").ToString()) %>'></asp:Label>
                      <br />
                      <div class='questionseditor'>
                      </div>
                      <br />
                      <div class="questionsdiv">
                          <asp:Repeater ID="childRepeater" runat="server" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("Relation2") %>'>
                              <ItemTemplate>
                              <div class="question">
                                  <asp:HiddenField ID="hdnQuestionType" runat="server" Value='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) %>' />
                                  <asp:HiddenField ID="hdnQuestionId" runat="server" Value='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionId\"]").ToString()) %>' />
                                  <asp:HiddenField ID="hfQuestionSortOrder" runat="server" Value='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"SortOrder\"]").ToString()) %>' />
                                  <asp:RequiredFieldValidator SetFocusOnError="True" ID="YesNoForScoreRequiredFieldValidator" runat="server"
                                      ControlToValidate="lstYesNoForScore" Display="Dynamic" ErrorMessage="Required<br />"
                                      Enabled='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "1" %>'></asp:RequiredFieldValidator>
                                  <asp:RequiredFieldValidator SetFocusOnError="True" ID="MemoRequiredFieldValidator" runat="server" ControlToValidate="txtMemoAnswer"
                                      Display="Dynamic" ErrorMessage="Required<br />" 
                                      Enabled='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "2" %>'></asp:RequiredFieldValidator>
                                  <asp:RequiredFieldValidator SetFocusOnError="True" ID="NumericAnswerRequiredFieldValidator" runat="server"
                                      ControlToValidate="txtNumericAnswer" Display="Dynamic" ErrorMessage="Required<br />"
                                      Enabled='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'></asp:RequiredFieldValidator>
                                  <asp:RegularExpressionValidator SetFocusOnError="True" Display="Dynamic" runat="server" ID="NumericTextRegexValidator"
                                      ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$" Enabled='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'
                                      ErrorMessage="*Invalid<br />" ControlToValidate="txtNumericAnswer"></asp:RegularExpressionValidator>
                                  <asp:RequiredFieldValidator SetFocusOnError="True" ID="RequiredFieldValidator1" runat="server" ControlToValidate="lstYesNoNonScored"
                                      Display="Dynamic" ErrorMessage="Required<br />" Enabled='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "5" %>'></asp:RequiredFieldValidator>
                                  <asp:Label ID="lblQuestionText" runat="Server" Text='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionText\"]").ToString()) %>'></asp:Label><br />
                                  <asp:RadioButtonList runat="server" ID="lstYesNoForScore" RepeatDirection="Horizontal"
                                      Visible='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "1" %>'>
                                      <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
                                      <asp:ListItem Text="No *" Value="0"></asp:ListItem>
                                  </asp:RadioButtonList>
                                  <asp:TextBox ID="txtMemoAnswer" runat="server" Visible='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "2" %>'
                                      TextMode="MultiLine" Rows="3" Width="100%"></asp:TextBox>
                                  <asp:TextBox ID="txtNumericAnswer" runat="server" Visible='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'
                                      cols="5"></asp:TextBox>
                                  <uc1:MultipleChoiceControl ID="MultipleChoiceControl1" runat="server" Visible='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "4" %>'
                                      QuestionId='<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem, "[\"QuestionId\"]")) %>' />
                                  <asp:RadioButtonList runat="server" ID="lstYesNoNonScored" RepeatDirection="Horizontal"
                                      Visible='<%#  Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(  DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "5" %>'>
                                      <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
                                      <asp:ListItem Text="No" Value="0"></asp:ListItem>
                                  </asp:RadioButtonList>
                                  <br />
                                  </div>
                              </ItemTemplate>
                          </asp:Repeater>
                      </div>
                      Comments for this Question Group (Required if score not awarded)
                      <asp:TextBox ID="txtGroupComments" runat="server" TextMode="MultiLine" Rows="3" Width="100%"></asp:TextBox>
                  </div>
              </ItemTemplate>
          </asp:Repeater>
      

      【讨论】: