I have the following code -
int lat = System.Convert.ToInt16(latTextBox1.Text);
This is happening on a changed event.
However my code is breaking on this line saying -
Input string was not in a correct format.
Where latTextBox1.Text = "" which is an empty string.
I think this is breaking because it cannot convert an empty string into a null value.
How can I modify my code to account for null values?
OK, based on your comment you could use:
int? lat = string.IsNullOrEmpty(latTextBox1.Text)
? (int?)null : Convert.ToInt32(latTextBox1.Text);
int? is a nullable int.
How about a simple:
int? lat = null;
int dummyLat;
if (Int32.TryParse(latTextBox1.Text, out dummyLat)
lat = dummyLat;
On a side note:
I' never convert strings in the TextChanged event ever! Why? Because it triggers an event upon every keypress! Use some other trigger to initiated the conversion (for example a button).
Well, Convert.ToInt16 isn't meant to convert an empty string into a null value... indeed it can't, given that the return type is a non-nullable Int16 (aka short).
I suspect you actually want something more like:
int lat;
if (int.TryParse(latTextBox1.Text, out lat))
{
// Use lat
}
else
{
// Invalid or empty input. Handle appropriately.
}
If you want to handle empty strings differently to invalid input, you'll need to do that explicitly - although you should also consider whether "just whitespace" is equivalent to "empty" or "invalid".
You could use the following method:
Int16.TryParse:
Or you could check if the string is not null or empty before performing the logic:
if (!string.IsNullOrEmpty(latTextBox1.Text)) {
lat = System.Convert.ToInt16(latTextBox1.Text);
}
http://msdn.microsoft.com/en-us/library/system.int16.tryparse.aspx
you should first check that the current value is not an empty one before trying to convert it to an integer, kindly check out the following snippet
int lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here
Update:
From your comment above, lat may hold the NULL value, so you will have to make it a nullable Int in order to make it hold the value NULL
consider this updated code snippet
int? lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat.value = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here by accessing the lat.value property
Note: latiture and longtitude values should be stored in a double datatype in order to preserve the precision.
You have to check for the string being set:
int lat = 0;
if (string.IsNullOrEmpty(latTextBox1.Text)
{
// Your null case here
}
else
{
lat = System.Convert.ToInt16(latTextBox1.Text);
}
Though:
int lat = 0;
if (!Int32.TryParse(latTextBox1.Text, out lat)
{
// Error handling here
}
is probably a better approach as it copes with non numeric input.
int lat = 0;
if (Int32.TryParse(laTextBox1.Text, out lat))
{
//success, textbox contained an int, now lat has the value of that int
}
else
{
//failure, textbox did not contain an int
}
int i = 0;
if (!Int32.TryParse(latTextBox1.Text, out i)) {
i = 0; // or default value;
}
One liner:
int lat = System.Convert.ToInt16(latTextBox1.Text.Length == 0 ? 0 : latTextBox1.Text);
Basically works like coalesce, if latTextBox1.Text does not have a value, set it to zero
otherwise the value from latTextBox1.Text
Related
I'm looking for a code to check if an element of my array of double is empty. I tried with isNaN, string.isNullOrEmpty and 0.0D but nothing to do, I still have this text : Not a Number.
So, do you know any code in C# which is able to check if an element in a an array of double is empty?
Here is my code:
if (!Double.IsNaN(d1.getChiffreAffaireBase()[keyIndex1]))
{
textBox43.Text = calcMargeCa(d1.getChiffreAffaireBase()[keyIndex1], d1.getChiffreAffairePlus()[keyIndex1]).ToString("0.00");
textBox44.Text = calcMargeCa(d1.getChiffreAffaireBase()[keyIndex1+1], d1.getChiffreAffairePlus()[keyIndex1+1]).ToString("0.00");
}
else
{
label13.Hide();
textBox43.Hide();
textBox44.Hide();
}
if you declare an array like this
double[] array = new double[12]; // elements cannot be null
all elements will be set to 0.
Declare it as nullable, if you really want
var array = new double?[12]; // elements can be null
var isEmpty = (array[6] == null);
or
var isEmpty = !array[6].HasValue;
Value types cannot not have a value (that is to say, they cannot be null) but you could use a Nullable<double> (or double? for short) which can be set to null if you want to indicate that it doesn't have a value. Here's an example:
double?[] array = new double?[12];
then for checking if it has a value you compare it to null:
if (array[6] == null){
// do your thing
}
Edit:
Off topic but now that you've posted your code I see that you're using double to represent money (Chiffre d'Affaire or Revenue) while that could work, you should use decimal instead
Double.IsNaN doesn't check for null values , check this for more or read the documentations about it
https://stackoverflow.com/a/7967190/6001737
instead you can use double?[] array = new double?[12]; which is Nullable and you can then check if a certain array value equals null
I am accessing an endpoint and getting JSON back. I loop through the object and I put the value in a double field. Sometimes the filed will be null. How do I handle the null case. Currently my code looks like:
double scanning_risk = double.Parse(JSONrecord[i].scanning_risk.ToString());
Just FYI. I was able to handle null errors with INT variables using the GetValueOrDefault() function like:
int Firm_Id = JSONrecord[i].Firm_Id.GetValueOrDefault();
Here is how I am handling strings:
string Deleted_At = JSONrecord[i].Deleted_At == null
? ""
: JSONrecord[i].Deleted_At.ToString();**
Is there a similar GetValueOrDefault() function for double or a similar way to handle the case when a double filed is null?
Thank you!
It should work the same as for ints:
double scanning_risk = JSONrecord[i].scanning_risk.DefaultOrEmpty();
Assuming, of course, that scanning_risk is a Nullable<double> field.
This code will return to you value or default value (0) for double:
double scanning_risk = 0;
double.TryParse(JSONrecord[i].scanning_risk.ToString(), out scaning_risk);
If you can have null in JSONrecord[i].scanning_risk use:
double scanning_risk = 0;
double.TryPerse(JSONrecord[i].scanning_risk == null ? "" : JSONrecord[i].scanning_risk.ToString(), out scanning_risk);
Also this method returns right default(0) value for double if string contains non numeric value.
Thanks eveyone.
This is what I ended up using:
double spread_charge = row.spread_charge == null
? 0
: double.Parse(row.spread_charge.ToString());
where my json class has double? spread_charge
double scanning_risk = 0;
if(!string.IsNullOrWhitespace(JSONrecord[i].scanning_risk.ToString())) {
scanning_risk = double.Parse(JSONrecord[i].scanning_risk.ToString());
}
I have a class that I am passing a value too from my textbox. I use int? in the class I am passing too, to allow null values. Every-time I execute it gives the input string is not in correct format error. How can I get it to allow the null value? I thought about creating an if statement that just passes string = "null". I put my code below thank you in advance.
This is what I use to pass the values to my class that gives the error when I leave it blank.
newGrid.EmployeeID = Convert.ToInt32(employeeIDTextBox.Text);
newGrid.JobID = Convert.ToInt32(JobIDTextBox.Text);
Variable declaration in my class that the info is passing to.
public int? JobID { get; set; }
Use TryParse instead:
Int32 employeeId;
newGrid.EmployeeID = Int32.TryParse( employeeIDTextBox.Text, out employeeId ) ? employeeId : null;
This does require multiple lines of statements. You could wrap TryParse to simplfy this, like so:
public static Int32? Int32TryParseSafe(String text) {
Int32 value;
return Int32.TryParse( text, out value ) ? value : null;
}
// Usage:
newGrid.EmployeeID = Int32TryParseSafe( employeeIDTextBox.Text );
int number;
bool result = Int32.TryParse(employeeIDTextBox.Text, out number);
if (result)
{
newGrid.EmployeeID=number;
}
else
{
//whatever you want to do for bad values
newGrid.EmployeeID=0;
}
You won't be able to convince Convert.ToInt32 to change its behavior, but you can easily get the effect you want yourself:
string employeeID = employeeIDTextBox.Text;
newGrid.EmployeeID = string.IsNullOrEmpty(employeeID) ? null : Convert.ToInt32(employeeID);
Note that while this is less verbose than some other options, you aren't as safe as you are with TryParse. If the user enters non-numeric characters this will fail.
why would this work
int collectionCharge = (int)cmdCheck.ExecuteScalar();
but this produces an exception
double collectionCharge = (double)cmdCheck.ExecuteScalar();
System.InvalidCastException: Specified cast is not valid.
why would it not be valid?
EDIT
I am trying to simply return a single result from a query, that gets the price of some freight. So I can't turn this into an int because it must have decimals, hence trying to cast to a double. I am still learning asp.net so if there's a better way to achieve this, please do point me in the right direction :)
EDIT 2
the full code with SQL...
using (SqlCommand cmdCheck = new SqlCommand("SELECT FREIGHT_PRICE FROM FREIGHT_QUOTER_BELNL_NEW WHERE CUSTOMER_NO = #CUSTOMER_NO AND COUNTRY = #COUNTRY AND ROUND(WEIGHT_FROM,0) < #WEIGHT AND ROUND(WEIGHT_TO,0) >= #WEIGHT AND SHIPVIA = '48';", connection))
{
double collectionCharge = (double)cmdCheck.ExecuteScalar();
FreightAmount = collectionCharge;
}
The problem here is that ExecuteScalar is returning an int which is boxed into an object. In order to convert to a double you must first unbox to an int then convert to a double
double collectionCharge = (double)(int)cmdCheck.ExecuteScalar();
Use the Convert.ToXXX to avoid invalid cast exceptions.
I.E
collectionCharge=Convert.ToDouble(cmdCheck.ExecuteScalar());
As it appears that ExecuteScalar returns an Object so the code:
double collectionCharge = (double)cmdCheck.ExecuteScalar();
Could still fail
With thanks to #DJKRAZE.
I updated my query to SELECT CASE(FREIGHT_PRICE AS FLOAT) which now works with the (double) cast.
double collectionCharge = (double)cmdCheck.ExecuteScalar();
After reading all answers, I had a case of receiving the Decimal values indeed, and the solution was easy!
I just declared the function as string and received the Decimal value as string!
public static string Sals_AccountExpensesGetSums(int accountID)
{
SqlParameterHelper sph = new
SqlParameterHelper(ConnectionString.GetWriteConnectionString(),
"sals_AccountExpenses_GetAllSums", 1);
sph.DefineSqlParameter("#AccountID", SqlDbType.Int, ParameterDirection.Input, accountID);
string res = sph.ExecuteScalar().ToString();
return res;
}
and in the business layer i changed the result to double!
public static decimal GetAccountExpensesSums(int accountId)
{
string res = "";
decimal sums = 0;
res = DBAccount.Sals_AccountExpensesGetSums(accountId);
// check so we will not have exception
if ( res != "")
sums = Convert.ToDecimal(res);
return sums;
}
and the result was perfect as needed: 889678.70
I would recommend using this code:
object o = c.ExecuteScalar();
if (o != null)
{
int x = Int32.Parse(o.ToString());
}
This does two things. First it makes sure that your c.ExecuteScalar() isn't returning null If it did so and you tried to cast, you'd have problems.
Second, it makes casting much simpler because it can be applied to pretty much all cases when reading from a query.
The object becomes a string. If you want it as a string, you're done.
If you want it as a boolean, check to see if that string.Equals("true")
If you want it as an int, Int32.Parse(string);
if you want it as a long, Int64.Parse(string);
Basically, you won't have to worry about fully understanding overloading/explicit conversion.
var doc = XDocument.Parse(inputXML);
this bombs out when "amount" node is not present. How can I check for existence prior to evaluating?
decimal amt;
var amount = doc.Descendants("amount").SingleOrDefault().Value;
bool amountValid = decimal.TryParse(amount, out amt);
I need to make sure "amount" is available prior to evaluating.
Can anyone help?
Thanks All,
~ck in San Diego
XElement provides explicit casts for most value types, including Nullable<Decimal>:
var amt = (decimal?)doc.Descendants("amount").SingleOrDefault();
From there you can check if amt is null or use its HasValue property.
Update: It's worth pointing out that the cast will throw a FormatException if the value is not a Decimal. If you still want to use TryParse, you can keep the code simple with a string cast:
decimal amt;
var amount = (string)doc.Descendants("amount").SingleOrDefault();
bool amountValid = decimal.TryParse(amount, out amt);
Internally, the string cast is implemented like Ben's sample, returning either null or element.Value.
Try this:
var amountElement = doc.Descendants("amount").SingleOrDefault();
if (amountElement != null)
{
decimal amt;
bool amountValid = decimal.TryParse(amountElement.Value, out amt);
// other code
}