提交表单后我的动态控件在哪里?

Where is my dynamic control after I submit the form?

我用转发器创建了一个动态表单。

<asp:repeater ID="fieldRepeater" OnItemDataBound="dataBound" runat="server">
    <itemtemplate>
        <div id="controlRow" class="row" runat="server">
            <div id="testContainer" class="col-md-2" runat="server">

            </div>
        </div>
    </itemtemplate>
</asp:repeater>

在代码隐藏中,我创建了我想在其中显示的字段。

Protected Sub dataBound(ByVal sender As Object, e As RepeaterItemEventArgs)
    dim temp as new DropDownList
    dim tempLabel as new label
    Dim testContainer As HtmlGenericControl = e.Item.FindControl("testContainer")

    'createField
    temp.ID = "testField" & e.Item.ItemIndex 'this is testField0
    temp.Items.Add(New ListItem("Not Used", 0))
    temp.Items.Add(New ListItem("Used", 1))
    temp.CssClass = "form-control"


    'createLabel
    tempLabel.ID = "testFieldLabel" & e.Item.ItemIndex
    tempLabel.AssociatedControlID = "testField" & e.Item.ItemIndex
    tempLabel.Text = dr("controlLabel")
    testContainer.Controls.Add(temp)
    testContainer.Controls.Add(tempLabel)
end sub

表单工作得很好,我什至可以用数据库中的数据预先填充它,但在我的提交处理程序中我的控件不存在:

Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
    Dim i As Int32 = 0
    For Each r As DataRow ...
        'db stuff
        Dim temp As New DropDownList
        temp = Me.FindControl("testField" & i.ToString)
        'db stuff            
        i += 1
    next
end sub

temp = Me.FindControl("testField" & i.ToString) 总是 nothing 谁能帮我找出原因?

我的 HTML 输出如下:

<div id="cntMain_fieldRepeater_testContainer_0" class="col-md-2">
    <label for="cntMain_fieldRepeater_testField0_0" id="cntMain_fieldRepeater_testFieldLabel0_0" style="color:#007AFF;">Activity</label>
    <select name="ctl00$cntMain$fieldRepeater$ctl00$testField0" id="cntMain_fieldRepeater_testField0_0" class="form-control">
        <option value="0">Not Used</option>
        <option value="1">Used</option>
    </select>
</div>

动态创建的控件需要在每次页面加载时(重新)创建,其中包括 PostBack。因此,您必须将 Repeater 的 DataBinding 移到 !IsPostBack 检查之外。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    fieldRepeater.DataSource = loadDataHere
    fieldRepeater.DataBind
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim i As Integer = 0
    For Each item As RepeaterItem In fieldRepeater.Items
        Dim temp As DropDownList = CType(item.FindControl(("testField" + i.ToString)),DropDownList)
        temp.BackColor = Color.Red
        i = (i + 1)
    Next
End Sub