【问题标题】:Find checkbox that tharts with id查找带有 id 的复选框
【发布时间】:2015-09-05 05:54:55
【问题描述】:

我正在尝试遍历一堆以特定 ID 开头的复选框。

这段代码看起来很正常,但它没有找到任何东西:

    Dim childc As Control
    Dim c as Control
    For Each c In Me.Page.Controls
        For Each childc In c.Controls
            If TypeOf childc Is CheckBox Then
                If CType(childc, CheckBox).Checked Then
                    If childc.ID.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
                        i = i + 1
                        Alerte(CType(childc, CheckBox).Text)
                        strSQL = "INSERT INTO A_ACTIVITES VALUES("
                        strSQL += Me.ID_PRESTATAIRE.Text + "," + childc.ID + ","
                        strSQL += ")"
                        oWebConnection.Execute(strSQL)
                    End If
                End If
            End If
        Next
    Next

它在第二行中断说

it's impossible to cast an objet of type 'ASP.masterpage_master' to 'System.Web.UI.WebControls.CheckBox

感谢您的帮助

【问题讨论】:

    标签: asp.net vb.net


    【解决方案1】:

    cchildc 声明为Control,而不是CheckBox

    c 的声明不可见,但我认为你犯了同样的错误。

    【讨论】:

    • 答案已更新。如果它不起作用,请发布您的 c 变量声明。
    • 对不起,它成功了,但是现在循环没有到达第六行,就像它没有找到任何复选框,虽然有很多。
    • 这是另一个问题;如您的错误中所述,您使用的是母版页,因此您可以查看一下:stackoverflow.com/questions/3720590/…
    • 会有所帮助,因为即使使用 Findcontrol 我也找不到复选框,但循环甚至没有到达它按 id 搜索的部分,它甚至没有找到任何复选框,不管它是否是动态的。
    • 至于母版页控件命名,我将其正确命名为 ctl00_indexBody_{ID}
    【解决方案2】:

    我找到了解决办法

    Protected Sub GererActivite(ByVal oControls As ControlCollection)
        Dim oControl As Control
        For Each oControl In oControls
            If oControl.HasControls Then
                GererActivite(oControl.Controls) ' récursivité
            ElseIf TypeOf oControl Is CheckBox Then
                If CType(oControl, CheckBox).Checked Then
                    If CType(oControl, CheckBox).Text.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
    
                    End If
    
                End If
            End If
        Next
    
    End Sub
    

    此函数通过控件集合运行,如果此集合的控件具有控件,我会使用相同的函数通过这些控件运行,直到找到没有控件的控件,如果它是复选框,我可以检查如我所愿。 它就像一个魅力。

    事实上,这是我老板的主意,我只是在吹牛,哈哈。

    希望它能帮助其他人。

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 2017-04-24
      • 2018-02-14
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      相关资源
      最近更新 更多