IIF 和 isNothing

IIF and isNothing

我有 3 个要连接的文本框。 fname, mname, lname

例如:

fname = Nat    ----     mname = Arnido    ----   lname = Congreso  

然后我希望他们使用命令按钮连接到另一个名为 fullname 的文本框中。

fullname = Congreso, Nat A.

但在另一种情况下,中间名是空的,全名应该是这样的。

fullname = Congreso, Nat

而且我发现很难删除中间名中的句点 (.)。

到目前为止,这是我的代码。

Me.fullname.Text = Me.lname.Text & ", " & Me.fname.Text & " " & IIf(IsNothing(Microsoft.VisualBasic.Left(Me.mname.Text, 1) & ""), "", (Microsoft.VisualBasic.Left(Me.mname.Text, 1)) & ". ")

文本框数据通常不是Nothing。它最多是一个空字符串:

Me.fullname.Text = Me.lname.Text & ", " & _
                   Me.fname.Text &  _
                   If(Me.mname.Text = String.Empty, _
                       "", _
                       " " & Left(Me.mname.Text, 1) & ".")

您还可以使用字符串 Replace 方法 remove/change 任何不需要的 characters/patterns。

mname.Replace(".", "")

我不会使用 IIf 或 Left。

    fullname.Text = lname.Text.Trim & ", " & fname.Text.Trim
    If Not String.IsNullOrWhiteSpace(mname.Text) Then
        fullname.Text &= " " & mname.Text.Trim.Substring(0, 1) & "."
    End If

如果我喜欢把它写成一个长语句,我会使用 If 运算符。

    fullname.Text = lname.Text.Trim & ", " & fname.Text.Trim & _
        If(Not String.IsNullOrWhiteSpace(mname.Text.Trim), " " & mname.Text.Substring(0, 1) & ".", "")