Check empty element array of double c# - c#

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

Related

String.IsNullOrEmpty check with Data Table cell

If I have a Data Table and I want to see if the value contained within a specific cell is empty I would use this.
foreach(DataRow row in DataTable.Rows)
{
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"].ToString());
}
but what happens if the value in row["MyColumn"] is null. Wouldn't the .ToString() throw an exception? Yet when I try the following ..
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]);
I get an invalid argument exception because the IsNullOrEmpty() method is looking for a string object.
So what is the proper way to check if a specific cell in a Data Table is empty or null?
Change your statement to this,
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]?.ToString());
?. means run the process .ToString() only if row["MyColumn"] is not null.
Basically just adding this for the sake of completeness... but if for some reason you aren't using C# 6 or above, you can always do it the "old fashioned way":
bool isEmpty = row["MyColumn"] == null || string.IsNullOrEmpty(row["MyColumn"].ToString());
You could instead use the Field<T>() method of the DataRow:
bool isEmpty = String.IsNullOrEmpty(row.Field<string>("MyColumn"));
This provides strongly typed access to the row values.
You can use it with other types too, so no need to parse int or DataTime, for example.
var myDate = row.Field<DateTime>("MyDate"); // DateTime
var myInt = row.Field<int>("MyInt"); // int
It also works with nullable types:
var myDate = row.Field<DateTime?>("MyDate"); // DateTime? (Nullable)
if (myDate.HasValue)
{
...
}

Cannot save empty text box value to database.(format is in int)

When i give empty value to bank region and cost centre it gives the error during saving to database.
Error:input string was not in a correct format.
objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text);
objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text);
this is the code i used.How i will save empty textbox value to database.
Try something like this:
objMEndorsement.BankRegion = string.IsNullOrWhiteSpace(txtBankRegion.Text) ? 0 : Convert.ToInt32(txtBankRegion.Text)
Replace
objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text);
objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text);
by
objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text??0);
objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text??0);
?? is null coalesce operator in c#
EDIT:
Best option would be to use tryParse like this
bool isInteger=int.TryParse(txtBankRegion.Text??0, out num1);
if(isInteger)
{
//insert into database
}
Try to use int.TryParse() this is better in handling conversion.
You can do it this way:
int bankRegion = 0; //Default value if wasn't able to parse
int.TryParse( txtBankRegion.Text, out value );
objMEndorsement.BankRegion = bankRegion;
Then you can do the same with the other field.
Make objMEndorsement.BankRegion NULLable and:
if(!string.IsNullOrWhiteSpace(txtBankRegion.Text))
objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text)
(This works if NULL is the initial value of the property objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text))
Otherwise (property still have to accept NULL):
objMEndorsement.BankRegion = string.IsNullOrWhiteSpace(txtBankRegion.Text) ? null : Convert.ToInt32(txtBankRegion.Text);
Remember that your database field must be NULLable also (otherwise you will get a DB error when trying to persist NULL).
make it nullable type by converting the value type to nullable type and then send it to database
yes use ternary operator and assign corresponding values
objMEndorsement.BankRegion = (txtBankRegion.Text.trim()) ? 0 : Convert.ToInt32(txtBankRegion.Text)

To pass null values to float data type to add it into list

I am trying to pass the null value to float data type as follow,
float? period_final_value = null;
and getting the value in period_final_value from the parsing xml string as follows
var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = float.Parse(action.Value);
and then adding this obtained value to list as follows
serie_line.data.Add(period_final_value);
Defined my list as follows
var serie_line = new { name = series_name, data = new List<float?>() };
Now, My issue is when I am trying to pass value,it shold get add to the list, and moment when no value is recognized then it should add null has the value in the place of empty value in list but I don't know I am not able to get it work properly...my web service crashes moment it counters any blank value...any help will be greatly appreciated...
plz note...the var serie_line..I am going to serialize it into JSON format so that I can use those values to plot chart.
It sounds like you might be looking for TryParse instead of Parse.
When you call period_final_value = float.Parse(action.Value);, Parse will either parse the string into a float or throw an exception. It will never return null.
To get the behavior you want, try something like this:
float temp_value = 0;
float? period_final_value = null;
if (float.TryParse(action.Value, out temp_value)) {
period_final_value = temp_value;
}
serie_line.data.Add(period_final_value);
If action.Value is a string representation of a number, then period_final_value will be that number. Otherwise, it will be null. You can then add it to your list of float? values.
At this line
float? period_final_value = float.Parse(action.Value);
you are loosing the nullable float. When it fails to parse (there is no value or the value is not a valid float), it throws instead of returning null. period_final_value will never have null as a value.
See gleng's answer to be able to set null to period_final_value.

How to return null if using SingleOrDefault() and searching a list of numbers for a number not in list?

When querying a list of positive numbers using SingleOrDefault(), how can I return null, or a custom value like -1, when a number isn't found in the list, instead of the type's default value (0 in this case)?
You could use:
var first = theIntegers
.Cast<int?>()
.SingleOrDefault(i => i == theValue) ?? valueIfNotFound;
This works by casting the items to a Nullable<int>, then using the null-coalescing operator to return the value you choose if null was returned (ie: not found).
Note this will throw if you have more than one matching item. If you don't want that behavior, use FirstOrDefault instead of SingleOrDefault.
You can use DefaultIfEmpty to specify a custom default value for an empty collection:
var value = numbers.Where(MyFilter)
.DefaultIfEmpty(-1) //or any other default value you want
.Single(); //OrDefault not needed; DefaultIfEmpty ensures there is an item
You have to change the type in your list to int? ( a nullable int ). The default value which you return will be 0 for an integer. For reference types it will be null. Without overloading the method you can't make the default retrurn value a custome value.
Maybe your question is simplified so this does not apply, but if you are only looking for a number you already know and want to return an arbitrary number if it's not in the list, you can use the Any-Extension method:
int numberToLookFor = 42;
int arbitraryReturnOnNotFound = 17;
int result = numbers.Any( n => n == numberToLookFor ) ? numberToLookFor : arbitraryReturnIfNotFound;

Handle nulls correctly

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

Categories

Resources