C# Infinite value error when casting/not casting - c#

I think this will be an easy one, i think im missing something.
if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))
this code gives me the error that when casting cant be a number that is infinite.
Ive also tried:
if (((int)row.Cells["Pareto"].Value <= 50) && ((string)row.Cells["Pareto"].Value != null))
if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != ""))
any help would be great!
Im using winforms in visual studio 10 using C#.
error: "When casting from a number, the value must be less than infinite"
More of the Code if your interested:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//countpg
//countPg++;
pgtothold = Convert.ToSingle(row.Cells["Qty"].Value);
countPg += pgtothold;
//if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))
if ((Convert.ToDouble(row.Cells["Pareto"].Value)) && ((int)row.Cells["Pareto"].Value <= 50)
{
//top 50
//top++;
tempTop = Convert.ToSingle(row.Cells["Qty"].Value);
top += tempTop;
}
else
if (((int)row.Cells["Pareto"].Value > 50) && ((int)row.Cells["Pareto"].Value <= 100) && (row.Cells["Pareto"].Value != ""))
{
//50-100
tempMidt = Convert.ToSingle(row.Cells["Qty"].Value);
tmid += tempMidt;
}
else

if ((row.Cells["Pareto"].Value != null) && ((int)row.Cells["Pareto"].Value <= 50))
I think you want this. If the thing is null, it doesn't evaluate the rest of the AND.

I suggest you to use:
var data = System.Convert.ToInt32(row.Cells["Pareto"].Value);
if( data <=50 )
{
----
}
that will fail to 0 if the content is DBNull ( if this is acceptable ), so your code will result cleaner and safer.

The result from the datatable is most likely of type decimal. So try this:
if (((decimal)row.Cells["Pareto"].Value <= 50.0m) && (row.Cells["Pareto"].Value != null))

Related

Delete item in List and carry on search [duplicate]

This question already has answers here:
How to remove elements from a generic list while iterating over it?
(28 answers)
Closed 3 years ago.
Is there any way I can search List<T> and remove empty items?
ObservableCollection ListOfTnAGroupAccs <Model>
foreach (var item in ListOfTnAGroupAccs)
{
if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
{
ListOfTnAGroupAccs.Remove(item);
continue;
}
}
it gives me "Collection was modified; enumeration operation may not execute"
I can use this
var nList = ListOfTnAGroupAccs.Where(l => l.Prefix != "" && l.ReportingGrp != "" && l.AccMngInitials != "" && l.Description != "").ToList();
But my curiosity is there any better way to do it?
You cannot remove items while iterationg them, and thus the exception. One way to do it is to do a regular backwards for loop:
for(int i = ListOfTnAGroupAccs.Length -1; i >= 0; --i)
{
var item = ListOfTnAGroupAccs[i];
if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
{
ListOfTnAGroupAccs.Remove(item);
continue;
}
}
The way it occurs is that you are iterating over collection which you want to modify in a loop, which may break iteration.
The best approach is to loop backwards:
for(int i = ListOfTnAGroupAccs.Length - 1; i >= 0; i--)
if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
ListOfTnAGroupAccs.RemoveAt(i);
Use a for-loop instead of foreach.
for (int i = ListOfTnAGroupAccs.Count-1; i>=0; i--)
{
if(ListOfTnAGroupAccs[i].Prefix == "" && ListOfTnAGroupAccs[i].ReportingGrp == "" && ListOfTnAGroupAccs[i].AccMngInitials == "" && ListOfTnAGroupAccs[i].Description == "")
{
ListOfTnAGroupAccs.RemoveAt(i);
continue;
}
}
We are going through the list in reverse order because we remove items. This way we prevent an IndexOutOfRangeException.

Linq to sql null value check in calculation

I have function which calculates quantity .Its working fine but some due to null values in field it does not return anything . these field can be null .i want to calculate only where both fields are not null. i think i need to use foreach but i dont know the way how can i use it here .
Help appreciated
private double Get_Quantity()
{
try
{
double sum = 0;
sum = (double)(from s in ManagerClass.oSqlData.table
where s.Demand.Order.Order_ID == Order_ID
where s.Demand.Order.Order_Date >= ManagerClass.startDate && s.Demand.Order.Order_Date <= ManagerClass.EndDate
select s.ValueA - s.ValueB ).Sum();
return sum;
}
catch
{
return 0;
}
}
Try like this;
sum = (double)(from s in ManagerClass.oSqlData.table
where (s.Demand != null && s.Demand.Order != null && s.Demand.Order.Order_ID == Order_ID)
&& (s.Demand != null && s.Demand.Order != null && s.Demand.Order.Order_Date >= ManagerClass.startDate && s.Demand.Order.Order_Date <= ManagerClass.EndDate)
&& s.ValueA != null
&& s.ValueB != null
select s.ValueA - s.ValueB).DefaultIfEmpty(0).Sum();

Input string was not in the correct format C#

I am curious as to why this is giving me an error:
Input string was not in a correct format.
This error occurs because the screen is null so it should fail the check and not cause an exception.
if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)
First check if it is not null. Also use double && as single checks both arguments. Also you are better off with double.TryParse in case when input is in not numeric.
if (textDisplay.Text != null && double.Parse(textDisplay.Text) >= -2147483647)
Better version:
double value = 0;
if (double.TryParse(textDisplay.Text, out value) && value >= -2147483647)
Use TryParse instead of Parse and it won't raise exception and return boolean if it is valid
double res = 0;
if(double.TryParse("asd", out res))
{
var a = res;
};
try && instead
if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)
or
double #num;
if(double.TryParse(textDisplay.Text, out #num) && #num >= -2147483647)
return #num;
if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)
You should use double '&':
if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)
Use TryParse so It will not throw any error when TextBox value is empty or null
double displayValue = 0;
double.TryParse(textDisplay.Text, out displayValue)
if (displayValue >= -2147483647)

Unchecked checkbox = textbox with value 0

I have this code:
for (int i = 0; i < ListView2.Items.Count; i++)
{
int a;
Int32.TryParse(((TextBox)ListView2.Items[i].FindControl("BrankyTextBox")).ToString(), out a);
if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked=false &&
a > 0)
{
RegisterStartupScript("alertBox2", "<script type='text/javascript'>alert('Error');</script>");
}
}
I want to when checkbox is unchecked the value of textbox must be only 0.
But this code only changes all checkbox in listview to unchecked... Have you some idea how to solve it?
You could clean this up a bit while you're at it:
for (Int32 i = 0; i < ListView2.Items.Count; i++)
{
Int32 a;
Int32.TryParse(((TextBox)ListView2.Items[i].FindControl("BrankyTextBox")).Text, out a);
if (!((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked && a > 0)
{
RegisterStartupScript("alertBox2", "<script type='text/javascript'>alert('Error');</script>");
}
}
In other words, use the not operator, which is !, to signify an inverse test. myVariable == false is equivalent to writing simply !myVariable.
You had only one = instead of == for comparison.
if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked == false || a > 0)
{
RegisterStartupScript("alertBox2", "<script type='text/javascript'>alert('Error');</script>");
}
You assign a value of true to the checkboxes in the if statement. You need to use a double =. Like this:
if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked==false ||
a > 0)
Your if is not doing what you expect
if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked=false
|| a > 0)
You're assigning false to the Checked property, and this statement is always false.
Currently, your if could be rewritten to be
if (false || a > 0)
Which is obviously not what you want. Add an = sign, making it
if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked == false
|| a > 0)
To fix the conditional expression. Another suggestion here would be to swap the conditions, benefiting from logical short-ciruiting:
if (a > 0 || ((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked == false)
In this case, when a > 0 is true the other conditions won't be evaluated resulting in (slightly!) better performance. See this other question for the details about short-circuiting.

Dataset in an If condition

I am still in the process of learning Asp.Net. I have a question . I was using an if condition in which i was checking dataset values. It is throwing me an exception whenever it is checking the condition as the dataset has not got any value. How to overcome this.
Code for this is here:
DataSet ds = merchant.getIsactiveIsconfirmedforcancelaccount(merchantID);
if (_merchant.PackageID == (int)CommonHelper.Package.Free && _merchant.AccountStatus.Contains("Awaiting"))
{
spnMerchantActiveStatus.InnerHtml = ApplicationData.MSG_AWAITING_CONFIRMATION;
}
***else if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" && (ds.Tables[0].Rows[0]["Active"]).ToString() == "N")***
{
_merchant.AccountStatus = "Cancelled";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else if(_merchant.PackageID != (int)CommonHelper.Package.Free && ds1.Tables[0].Rows.Count == 0 && (ds2.Tables[0].Rows[0]["ConfirmationSrc"]).ToString() == "Admin")
{
_merchant.AccountStatus = "Free Trial";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
The exception here is "There is no row at position 0."
Seems like you do not have any rows in your tables[0]. You can add condition to check is rows > 0 and then continue with other conditions in the IF.
You are assuming you have rows in your DataSet.
Instead of
if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
you should do something like
if ((ds.Tables[0].Rows.Count() > 0) &&
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
But you really need to do fuller error checking than just that one condition affectin you right now.
EDIT: If it's not obvious why the above works, read up on short-circuiting of logical operators: http://msdn.microsoft.com/en-us/library/2a723cdk(VS.71).aspx
Try changing your else statement :
else if (
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
{
_merchant.AccountStatus = "Cancelled"; spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
To
if ((null != ds.Tables[0]) && ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True") && ((ds.Tables[0].Rows[0]["Active"]).ToString() == "N"))
So that you check that the data set is not null before you check conditions on it.
or (as other posters say) check that you actually have rows in the dataset.
ds.Tables[0].Rows.Count() != 0

Categories

Resources