• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 12126
  • Last Modified:

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
 
0
dotnet0824
Asked:
dotnet0824
  • 3
  • 2
  • 2
  • +2
2 Solutions
 
hongjunCommented:
You wont be able to store System.DBNull.Value in a string variable.

hongjun
0
 
dotnet0824Author Commented:
then whatz the solution for this. I want to pass System.dbnull.value to the stored procedure if value not passed in the variable.
0
 
hiteshgoldeneyeCommented:
where you are using your query use the following pseudo code

if string.empty then
     query = "insert System.dbnull.value in DB"
else
    query = "insert strname in DB"
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
icrCommented:
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
0
 
dotnet0824Author Commented:
I couldnt find such thing string.IsNullorEmpty ...
0
 
kumar_jacCommented:

hi,
 Please try this

Public object StringEmptyToDBNull(string str)
{
     return  str == string.Empty ? DBNull.Value : str;
}

Call this function every where you want
0
 
icrCommented:
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;
}
0
 
icrCommented:
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)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now