Link to home
Start Free TrialLog in
Avatar of dotnet0824
dotnet0824

asked on

Using IFF statement in C#

I want to use IIF statement equivalient in C# coding
if strName is Empty I want to pass System.DBnull.value to be inserted in DB else strName would be passed

string strName;
strName = TxtName.text.value;

strName = string.empty  ? System.dbnull.value :  strName

Whatz the correct syntax. I get some Errors
 
Avatar of hongjun
hongjun
Flag of Singapore image

You wont be able to store System.DBNull.Value in a string variable.

hongjun
Avatar of dotnet0824
dotnet0824

ASKER

then whatz the solution for this. I want to pass System.dbnull.value to the stored procedure if value not passed in the variable.
SOLUTION
Avatar of Hitesh Manglani
Hitesh Manglani
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also, String.Empty is a constant that represents an empty string. If you want to check if a particular string is empty you can use string.IsNullOrEmpty(strName);
So it would be:
if (string.IsNullOrEmpty(strname))
    // Insert System.DbNull
else
    // Insert strname
I couldnt find such thing string.IsNullorEmpty ...
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
kumar_jac's is actually a pretty good solution when combined with hiteshgoldeneye's idea of only inserting it when you are building the query. You will need to alter it to cast str to an object though:

public object StringEmptyToDBNull(string str)
{
    return (str == string.Empty) ? DBNull.Value : (object)str;
}
Sorry, you'll also want to check if the string is null, just for robustness:

public static object StringEmptyToDBNull(string str)
{
     return (str == null || str == string.Empty) ? DBNull.Value : (object)str;
}

(Also note that it can be static)