VB6 issue with NULL

后端 未结 2 1686
猫巷女王i
猫巷女王i 2021-01-16 21:23

I\'m working on an application in VB6. I came across what seems to be a small issue, however it is annoying and I am unable to fix it. What I\'m doing is trying to pass 2 va

2条回答
  •  温柔的废话
    2021-01-16 22:08

    Just to answer your original question: first, "" isn't Null, it's an empty string, which is not the same thing. If you want to turn a Null into an empty string, just add an empty string to it: Null & "" evaluates to "".

    This can be a handy trick. It comes up a lot in situations where you're trying to populate a control (say, a label or text box) with a value from a database table. For example (assume txtMyBox is a text box and rs is an ADO Recordset object):

    txtMyBox = rs.Fields("myField")
    

    Now, if the field doesn't contain any data, this will throw an error, since you can't set a text box's value to Null. To fix the problem, you could do this:

    If Not IsNull(rs.Fields("myField")) Then
        txtMyBox = rs.Fields("myField")
    Else
        txtMyBox = ""
    End If
    

    This is cumbersome. You could streamline it by using the ternary operator:

    txtMyBox = IIf (Not IsNull(rs.Fields("myField")), rs.Fields("myField"), "") 
    

    Which is better, but still cumbersome. Fortunately, you can also just do this:

    txtMyBox = rs.Fields("myField") & ""
    

    Because concatenating an empty string to a string has no effect on it, and concatenating an empty string to a null value gives an empty string.

提交回复
热议问题