通过动态创建的控件环路 [英] Loop through Dynamically Created Controls

查看:108
本文介绍了通过动态创建的控件环路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是动态地创建一批下拉列表,然后我通过他们要循环和更新这些值的数据库,但我现在面临的问题是,我创建的下拉列表,但是当我通过他们回环路的面板不再。我不知道为什么,但是当我调试我的pnlTeacherSelect 50控制计数的权利,直到我preSS调用prcChoose的按钮。

What I am trying to do is dynamically create a bunch of dropdown lists and then I want to loop through them and update the database with those values, but the problem I am facing is that I create the dropdown lists, but then when I go back to loop through them they are no longer in the panel. I don't know why but when I am debugging I have a count of 50 controls in pnlTeacherSelect right up until I press the button that calls prcChoose.

调用页面加载

Sub prcSetTeachers()
    For Each Subject In ds.Tables("Subject").Rows
        Dim Temp As New DropDownList
        pnlTeacherSelect.Controls.Add(Temp)
        Temp.ID = "drp" & Subject.Item(0) & "s" & Child.Item(0)
    Next
End Sub

叫上点击一个按钮

Sub prcChoose()
    For Each DropDownList In pnlTeacherSelect.Controls.OfType(Of DropDownList)

    'This is never executed

    Next
End Sub

任何想法是什么引起的呢?在此先感谢!

Any ideas what's causing it? Thanks in advance!

推荐答案

您必须重新创建所有动态创建的控件上的每个回发(负载事件最晚)。
你还必须确保他们获得相同的ID之前触发事件和维护的ViewState。

You have to recreate all dynamically created controls on every postback(in load event at the latest). You also have to ensure that they get the same ID as before to trigger events and maintain ViewState.

如果你知道控件创建的数量被追加到控制-ID(可以存储在的ViewState ),您可以得到从计数器变量的ID 。然后,你可以在正确的ID创建这些页面的的init 事件。

If you know the number of controls to create(which could be stored in ViewState) you can derive the ID from the counter variable by appending it to the control-id. Then you can recreate them with the correct ID in page's init event.

Recommandable读数:

Recommandable readings:

  • TRULY Understanding Dynamic Controls
  • Page-Lifecycle

您也可以使用内置的数据绑定控件中的一个像直放站自动做到这一点。你只需要设置其数据源和呼叫的DataBind ()

Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their DataSource and call DataBind().

下面是对类似的问题我回答的与实现:

Here are answers of me on similar questions with implementations:

  • C#
  • VB.NET (+ C#)

这篇关于通过动态创建的控件环路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆