我用转发器创建了一个动态表单。
<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
表单工作得很漂亮,我甚至可以用db中的数据预先填充它,但在我的提交处理程序中,我的控件不存在:
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>
答案 0 :(得分:1)
动态创建的控件需要在每个页面加载上重新创建,并且包括PostBack。因此,您必须在!IsPostBack
检查之外移动Repeater的DataBinding。
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