0

我有一个带有许多下拉列表框的表单。我根据表格的值显示或隐藏表格中的每一行,然后将 requiredfieldvalidator 添加到该行中包含的文本框中。我在每个下拉列表的 selectedindexchanged 事件上执行此操作,其代码如下所示:

Protected Sub cbOffCover_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbOffCover.SelectedIndexChanged

    If cbOffCover.SelectedValue = "N" Then
        OffCoverRow.Visible = True
        Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
        With rfOffcover
            .ControlToValidate = txtOffCover.ID
            .SetFocusOnError = True
            .ErrorMessage = "*"
            .ForeColor = System.Drawing.Color.Red
        End With
        OffCoverCell.Controls.Add(rfOffcover)
    Else
        OffCoverRow.Visible = False
        Dim c As Control
        For Each c In OffCoverCell.Controls
            If c.ID = "rfOffCover" Then
                OffCoverCell.Controls.Remove(c)
            End If
        Next c
    End If

End Sub

然后,我为每个下拉列表重用此代码以显示/隐藏不同命名的行并将验证应用于不同的文本框。

我的问题是有没有更好的方法来做到这一点?我不知道具体是怎么做的,但我不禁认为我不必为每个下拉列表一遍又一遍地编写这么多代码(或复制/粘贴)。是否可以编写一个可以完成工作的函数/类,而我可以直接调用它?可能看起来很基本,但我是 asp/vb 的新手。非常感谢

4

1 回答 1

2

你可以把它放在一个返回布尔值的函数中。当您调用该函数时,将组合框本身以及您想要验证的任何值传递给它。如果匹配,则返回 true。尝试这样的事情:

Public Function ValidateComboBox(someComboBox as ComboBox, expectedValue as String)
  Dim result as Boolean = False
  If someComboBox.SelectedValue = expectedValue Then
        result = True
        OffCoverRow.Visible = True
        Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
        With rfOffcover
            .ControlToValidate = txtOffCover.ID
            .SetFocusOnError = True
            .ErrorMessage = "*"
            .ForeColor = System.Drawing.Color.Red
        End With
        OffCoverCell.Controls.Add(rfOffcover)
  Else
        OffCoverRow.Visible = False
        Dim c As Control
        For Each c In OffCoverCell.Controls
            If c.ID = "rfOffCover" Then
                OffCoverCell.Controls.Remove(c)
            End If
        Next c
  End If

  Return result

End Function

当然,修改它以满足您的需求。也许您只返回值,并在控件的 SelectedIndexChanged 方法中执行其他操作。

于 2013-07-17T13:00:53.677 回答