【问题标题】:ASP .NET Dropdownlist.Selectedvalue not updating iterating through dynamically created controlsASP .NET Dropdownlist.Selectedvalue 不更新迭代通过动态创建的控件
【发布时间】:2013-05-12 00:52:21
【问题描述】:

动态创建的下拉列表控件中的 selectedvalue 属性没有更新:

我有一个 ctlProductosFormatos 类型的自定义控件,其中包含一个组合和其他控件。我在其他地方动态创建了这个自定义控件,然后遍历动态创建的控件中的所有组合,以使用我想要的值从另一个虚拟下拉列表中复制它们上的项目列表。

这段代码中的控件是右迭代的,combo也是右填充的。我的问题是我想将每个组合上的 selectedvalue 保持在与项目更新之前相同的值,但这失败了。

如果我进入代码并只运行第一个组合的迭代,然后跳出循环,则此组合将正确填充并使用正确的选定值,但如果我运行完整循环,则设置所有组合与最后一个组合具有相同的值,所以我想这与我为所有迭代实例化相同的控件有关,但在我的代码中似乎不是这样。

    Dim ControlFormato As ctlProductosFormatos
    ' Iterates through custom controls collection, IEnumerable(Of ctlProductosFormatos)
    For Each ControlFormato In Controles
        ' Get the dropdownlist inside the current custom control
        Dim ControlComboFind As Control = ControlFormato.FindControl("cmbFotoFormato")
        Dim ControlCombo As DropDownList = CType(ControlComboFind, DropDownList)
        ' Get the currently selected value in the dropdownlist
        Dim ValorSeleccionado As String = ControlCombo.SelectedValue

        ' Clear the items in the current combo,and fills with the ones in a dummy combo
        ControlCombo.Items.Clear()
        ControlCombo.Items.AddRange(ComboPatron.Items.OfType(Of ListItem)().ToArray())

        ' Sets the current combo selected item with the previously saved one
        ControlCombo.SelectedValue = ValorSeleccionado
    Next

【问题讨论】:

    标签: .net dynamic drop-down-menu selectedvalue


    【解决方案1】:

    问题在于 ViewState。如果您正在动态修改 DropDownList () 中的项目,它的 ViewState 将不会更新,因此当您回发值时,框架将在控件的 ViewState 内查看发送的值,但该值将丢失,因此 SelectedValue 属性不会被设置。如果您想使用发布的值,请从 Request.Form[ddlName.ClientID] 获取它们(我不确定 ClientID 是否是正确的索引,但主要思想是这个)。

    【讨论】:

    • 感谢您的提示,但问题与此无关,因为如果我打破循环仅处理一个元素,则处理的项目工作正常。我终于明白问题出在组合复制方法中。似乎使用此方法在组合之间共享项目,并且更改其中一个中的 selectedvalue 会影响其他项目。我发布了解决我的问题的更改。无论如何,感谢您的想法;)
    【解决方案2】:

    正如我在彼得的评论中所写,问题在于组合项目重复,其行为类似于“共享项目”。我把这段最丑和更长的代码替换掉了重复行,问题就解决了。希望对您有所帮助。

        ' Clear the items in the current combo,and fills with the ones in a dummy combo
        ControlCombo.Items.Clear()
        ' THIS LINE HAS BEEN COMMENTED AND REPLACED FOR THE FOLLOWING CODE
        ' ControlCombo.Items.AddRange(ComboPatron.Items.OfType(Of ListItem)().ToArray())
    
            Dim LSource As ListItem
            Dim LDestination As ListItem
            For i = 0 To ComboPatron.Items.Count - 1
                LSource = ComboPatron.Items(i)
                LDestination = New ListItem(LSource.Text, LSource.Value)
                ControlCombo.Items.Add(LDestination)
            Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-28
      • 2012-04-30
      • 1970-01-01
      • 2019-01-01
      • 2012-03-19
      • 2014-07-14
      • 1970-01-01
      • 2013-11-04
      相关资源
      最近更新 更多