ASP.Net - 减少重复验证代码 - VB

时间:2013-07-17 09:56:41

标签: asp.net vb.net

我有一个包含许多下拉列表框的表单。我根据其值显示或隐藏表的一行,然后在该行中包含的文本框中添加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的新手。非常感谢

1 个答案:

答案 0 :(得分: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方法中执行其他操作。