Is it possible to rewrite this into a single line of code?
if (txtInvoiceDate.Text != "")
{
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}
Yes
I have been reading about the ?: operator. I wasn't sure how this
would work in this situation. I have never used it in this case
So, according to your code you can change it to
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = txtInvoiceDate.Text != "" ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
but it will be better to use string.IsNullOrWhiteSpace()
query.Parameters.Add("#InvoiceDate", SqlDbType.SmallDateTime).Value = !string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
Read more about ?: Operator
Short answer: yes
Long answer:
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DBNull.Value : DateTime.Parse(txtInvoiceDate.Text.ToString());
Related
I have this weird error.
On this code, as you can, I have a query on database, return it as DataTable and explicitly declared it null. Now I have a condition to check this if this is null and pass it to a string variable. Everything works fine. I receive an empty string. No exception found.
DataTable dtDateUploaded = _BL.GetRecordByDataTableResults();
dtDateUploaded = null;
string strUploadedDate = dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString();
But when I used the same condition and pass it directly to a Label control for example (and not use a string variable), I get an object reference error. I wonder why do I get an object reference error if I just used the same code on my string variable above?
LblRecordCount.Text = "Record Uploaded last: " + dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString();
And the weird part is that this works:
LblRecordCount.Text = "Record Uploaded last: " + strUploadedDate;
You get this error because, in the second example, the + operator has precedence over the == operator so you are trying to concatenate the "Record Uploaded last" string to a null variable.
Instead, in the first example, the = operator has lower precedence than the == operator and no error occurs because the ternary operators are evaluated before the assignment.
You should use brackets to group the ternary operators logic together
LblRecordCount.Text = "Record Uploaded last: " + (dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString());
See MSDN on C# Operators
In my table of MySQL Db I have the field Check.
The value memorized on the field Check it could be : null or -1.
When the value memorized on the field Check is null or -1 I need in return the xxx value. and I have tried :
string Check = sdr["Check"] == DBNull.Value || sdr["Check"] == "-1,00" ? "xxx" : sdr["Check"].ToString();
Without success because the output is always -1,00.
How to do resolve this?
Please help me, thank you so much in advance.
The problem is that you are comparing the wrong objects. The values returned from System.Data result sets are wrappers around the actual value. What you want are the typed versions. Basically, the check should look like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = sdr.IsDBNull(checkIndex) || (sdr.GetString(checkIndex) == "-1,00") ? "xxx" : sdr.GetString(checkIndex);
If you "Check" is actually a number, you may want to use the IntValue("Check") call, just to deal with globalization issues if your app is ever deployed where they use a "." instead of a "," for your decimal point.
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx for the full API.
If your MySQL database is not set to use the same locale formatting as your C# application, your assumptions about number formats could be incorrect. To make a more robust version of your check, I would recommend something like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = "xxx";
double checkValue = sdr.IsDBNull(checkIndex) ? -1 : Convert.ToDouble(sdr[checkIndex]);
if (checkValue != -1)
{
Check = checkValue.ToString(CultureInfo.CurrentCulture);
}
If the data type is decimal 10,2 you need Convert.ToDecimal the value :
string Check = (sdr["Check"] == DBNull.Value || Convert.ToDecimal(sdr["Check"]) == -1) ? "xxx" : sdr["Check"].ToString();
You can compare a string empty or null by below code
string str = Your string
if(String.IsNullOrEmpty(str))
{
if yes, it comes here
}
else
{
if not, it comes here
}
The String.IsNullOrEmpty() is a bool type.
The following conversion doesn't work.
Error:"Only assignment, call, increment, decrement & new object can be
used as a statement"
VB.net
objUser.Email = IIf(IsDBNull(drow("Email")), "", drow("Email"))
C#
objUser.Email == (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
I need it in C#. Any ideas??
In C# = is asignment operator and == is comparison operator
Remove == and replace with =.
Assuming that drow is DataRow
objUser.Email = (drow.IsNull("Email") ? String.Empty : drow["Email"].ToString());
?: is ternary operator which always returns a value. In your case that value is being assigned to objUser.Email.
You have accidentally, used comparison operator instead of assignment operator.
objUser.Email == (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
should be, as you are not doing comparision, its an assignment.
objUser.Email = (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
You're using equal operator instead of assignment operator in the C# variant.
Change the == to = since what you want is assignment.
objUser.Email = (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
Try this:
objUser.Email = (DBNull.Value == drow("Email")) ? "" : drow("Email"));
See the Documentation for DbNull - where you will find examples:
From MSDN
private string AddFieldValue(string label, DataRow row,
string fieldName)
{
if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
}
I'm missing something, how do I make this work?
var now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths( -14 ).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ] == String.Empty ? now.ToShortDateString();
Basically when the page loades if sd and/or ed is blank, then fill the date with my pre-defined stuff.
You are forgetting a : and the part after it.
The conditional operator has three parts:
predicate (Request.QueryString["sd"] == String.Empty)
true branch
false branch
You are missing the false branch syntax and value.
I would write it as:
string loadStartDate = string.IsNullOrWhitespace(Request.QueryString["sd"])
? now.AddMonths( -14 ).ToShortDateString()
: Request.QueryString["sd"];
Note:
string.IsNullOrWhitespace is new to .NET 4.0, so use string.IsNullOrEmpty for prior versions.
It should be like:
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths
( -14 ).ToShortDateString():SOME OTHER VALUE;
The syntax for the conditional operator is:
condition ? truevalue : falsevalue
You are missing the colon and the value for when the conditon is false.
You can use the conditional operator for this, but then it gets a little repetetive. Just do like this:
DateTime now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"];
if (String.IsNullOrEmpty(loadStartDate)) loadStartDate = now.AddMonths(-14).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ];
if (String.IsNullOrEmpty(loadEndDate)) loadEndDate = now.ToShortDateString();
Trying to figure out how to get the null coalescing operator to work in a foreach loop.
I'm checking to see what a string ends with and based on that, route it to a certain method. Basically what I want to say is....
foreach (String s in strList)
{
if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type";
}
In attempting to do this, of course you get the "Operator ?? cannot be used on type bool and type string." I know there is other ways to do it, just want to see how it can be done with null coalescing.
Have a good weekend.
#Richard Ev: Oh yes of course. Switch, if else, etc. Was just curious how it
could be handled
#Jon Skeet: After reading your comments it hit me, this is just bad! I am
interested in two file extensions basically. If a file ends with "abc" for
instance, send to method 1, if the file ends with "xyz" send to method 2. But
what if a file ends with an extension of "hij"...boom, you're done.
Thanks to Brian and GenericTypeTea as well for the thoughful input
I'm content calling it closed.
It looks like you want to use the normal ternary operator, not null coalescing. Something like:
(s.EndsWith("d") ? Method1(s) : Method2(s)) ?? "Unknown file type";
This is equivalent to:
string result;
if (s.EndsWith("d"))
result = Method1(s);
else
result = Method2(s);
if (result == null)
result = "Unknown file type";
return result;
I think you want a combination of the conditional (ternary) operator and the null coalescing operator:
foreach (String s in strList)
{
string result = (s.EndsWith("d") ? Method1(s) : Method2(s))
?? "Unknown file type";
}
In simple english, this will do the following:
If s ends with d, then it will try Method1.
If s does not end with d then it will try Method2.
Then if the outcome is null, it will use "Unknown file type"
If the outcome is not null, it will use the result of either A or B
I think the compiler gave you the appropriate answer, you can't.
Null coalescing is essentially this if statement:
if(x == null)
DoY();
else
DoZ();
A boolean value cannot be null, so you can't coalesce it like that. I'm not sure what your other methods return, but it seems like you want a simple || operator here.
You should first use the ?? null coalescing operator to guard against a null s reference. Then use the ? ternary operator to choose between Method1 and Method2. Finally use the ?? null coalescing operator again to provide the default value.
foreach (string s in strList)
{
string computed = s;
computed = computed ?? String.Empty;
computed = computed.EndsWith("d") ? Method1(s) : Method2(s);
computed = computed ?? "Unknown file type";
}