循环通过不同的下拉列表

时间:2015-01-14 17:02:44

标签: asp.net .net vb.net

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

  • 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

1 个答案:

答案 0 :(得分:2)

是的,你可以。 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)