【问题标题】:Looping through different dropdown lists循环浏览不同的下拉列表
【发布时间】:2015-01-14 17:02:43
【问题描述】:

我在一个页面上有多个控件,它们都相似且都已编号。例如,我有多个这样的月份控件:

  • Replacement1MonthDropDownList
  • Replacement2MonthDropDownList
  • Replacement3MonthDropDownList

但是当我有适用于所有控件的通用代码时,我需要一个大的Select Case 语句,如下所示:

Select Case Count
    Case 1
        Call Me.FillReplacements(rf.Replacements(0), Me.Replacement1MonthDropDownList, Me.Replacement1AmountTextBox, Me.ReplacementSaveButton)
    Case 2
        Call Me.FillReplacements(rf.Replacements(0), Me.Replacement1MonthDropDownList, Me.Replacement1AmountTextBox, Me.ReplacementSaveButton)
        Call Me.FillReplacements(rf.Replacements(1), Me.Replacement2MonthDropDownList, Me.Replacement2AmountTextBox, Me.SplitButton1)

是否可以遍历控件并通过名称获取它们——只需将名称中的数字替换为当前循环中的Count

对不起,我是 Visual Basic 的新手! :S

【问题讨论】:

    标签: asp.net .net vb.net


    【解决方案1】:

    是的,你可以。 Page 类(在本例中为Me)有一个FindControl 方法,它允许您按名称查找控件。因此,例如,您可以执行以下操作:

    Dim monthControl As Control = Me.FindControl("Replacement" & Count.ToString() & "MonthDropDownList")
    Dim splitControl As Control = Me.FindControl("SplitButton" & Count.ToString())
    

    如果您需要将它们转换为更具体的类型,您可以使用DirectCast。例如:

    Dim monthControl As DropDownList = DirectCast(Me.FindControl("Replacement" & Count.ToString() & "MonthDropDownList"), DropDownList)
    

    或者,也许最好是,您可以创建一个控件数组,以便您可以通过索引访问它们。例如,如果你定义了一个这样的数组:

    Private monthControls() As DropDownList = {Replacement1MonthDropDownList, Replacement2MonthDropDownList, Replacement3MonthDropDownList}
    

    然后你可以像这样通过索引访问它:

    Dim currentMonthControl As DropDownList = monthControls(Count)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 2020-10-14
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      相关资源
      最近更新 更多