Casting from CLR types to SQL types

1/ When my textbox is empty, doing:
pm=Mysqlcommand.parameters.add(new sqlparameter("@Address",sqldbtype.char,50))
pm.value=Mytextbox.text

sends a string with empty spaces to my table in SQL server.
The way I avoid that I do:

if Mytextbox.text=string.empty then
pm.value=sqlstring.null
else
pm.value=Mytextbox.text
end if

My Question: I want to do that automatically with only one instruction and without doing If...then..else....

2/ How to cast string variables to sqlstring like from MyTextBox.text to a sqlstring type
3/ Sometimes, my object : Myobject is not set to an instance, but I still want to assign it to my parameter
pm.value=MyObject.property
Is that possible

4/ Do u know hoe to cast other types: Integer to SqlInt64 and vice versa;

Thanks a lot




Answer this question

Casting from CLR types to SQL types

  • Jessica Alba

    1. String.Empty or "" has the length 0, which is not null.

    3. property must be the static field of MyObject.



  • yzhu

    Generally, if you don't instantiate an object but want to use its properties/members, those properties/members have to be static.

  • Prabhakarbn

    thanks

  • AndyPham

    thanks a lot. I undestand 2 and 4. For question 1 and 3:
    1/ Why does an empty string send a string full of empty spaces having the lenght declared in sqlparam
    3/ Sometimes, my object : Myobject is not set to an instance, but I still want to assign it to my parameter
    pm.value=MyObject.property
    Actually, I declare property as integer and the sqlparam is of type SqlInt32
    But in this case, I receive the error when MyObject has a value of nothing
    Thanks


  • iortizvictory

    1) if statement is unavoidable because zero length string is not null.

    2) there's no way to cast a string to a SqlString. But you could use SqlString(String) constructor to construct a new SqlString.

    3) It's ok if the property of MyObject matches the parameter type.

    4) SqlInt64 has the constructor SqlInt64(long). And you can get a long value of a SqlInt64 by using its Value property.



  • SpoonmanUK

    can u pls explain more what u mean by 3/ static member and what s its significance in our case


  • Casting from CLR types to SQL types