在事件处理程序中传递文本框值

时间:2012-04-01 14:17:17

标签: .net vb.net winforms events

我有以下代码来验证两个文本框条目,以确保它们是有效日期。我的问题是我无法弄清楚如何将文本框值作为参数传递,因此我可以使用该方法来处理两个不同文本框的文本验证。以下是我到目前为止的情况:

Private Sub txtBirthdate_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtBirthdate.Validating, txtSpouseBirthday.Validating

    Try
        If String.IsNullOrWhiteSpace(sender.ToString) Then
            'Do Nothing
        Else
            Dim ReturnDate As DateTime
            ReturnDate = validator.CheckIsValidDate(sender.ToString)
            txtBirthdate.Text = ReturnDate.ToShortDateString
        End If
    Catch ex As Exception
        Throw
    End Try

End Sub

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要将sender对象转换为TextBox以获取属性:

Private Sub txtBirthdate_Validating(sender As Object, e As CancelEventArgs) _
  Handles txtBirthdate.Validating, txtSpouseBirthday.Validating

  Try
    With DirectCast(sender, TextBox)
      If String.IsNullOrWhiteSpace(.Text) Then
          'Do Nothing
      Else
          Dim ReturnDate As DateTime
          ReturnDate = validator.CheckIsValidDate(.Text)
          .Text = ReturnDate.ToShortDateString
      End If
    End With
  Catch ex As Exception
      Throw
  End Try
End Sub