If Condition not Working ASp.Net? - c#

i am trying to check condition before entering into it but it is entering in wrong condition
my conditions are ,
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() == "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() != "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) > 10000000)
the values are,
T_B_CX = 0 and T_B_C = 2500000000
it must enter the fist condition i mentioned but it is entering in second condition???
Hopes for your suggestion thanks in advance

you can convert to int and do the comparison as below
if (Convert.ToInt(Target.Tables[0].Rows[0]["T_B_CX"].ToString()) == 0 && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
may be when we get ToString of cell value it returns not exactly string equal to "0", debug and see which value you get for Target.Tables[0].Rows[0]["T_B_CX"].ToString()

There is no code between the two conditions, so the first one is taken as expected, then the second one is evaluated till the != 0.
Try to write something like this
// Convert everything just one time here
int tbcx = Convert.ToInt32(Target.Tables[0].Rows[0]["T_B_CX"]);
long tbc = Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]);
if(tbcx == 0 && tbc >= 100000)
// code here
else if(tbcx != 0 && tbc > 2500000000)
// code here
Also try to avoid the conversion of an integer value to a string and then check against a string.
It makes no sense. If an integer is stored in that table then convert it to an integer and check against an integer.

Related

How do I make a text box accept only int between 1 to 6 [duplicate]

This question already has answers here:
asp.net validation to make sure textbox has integer values
(12 answers)
Closed 4 years ago.
I've been trying to figure out how to do this for hours. How do I make the program takes only values from 1 to 6 or else it crashes?
"user only enters acceptable credit hours-- every credit hours entered is an integer between 0 and 6 and nothing else. In this case, any invalid or bad or empty input data will cause a run-time error, which is expected and is fine."
this is one of the methods i tried that did not work. I need to find out how to make the program just give a runtime error. I dont need to keep asking for input or display a message saying "error"
creditHours = double.Parse(tb_credit.Text);
if (creditHours != 1 || creditHours != 2 || creditHours != 3 ||
creditHours != 4 || creditHours != 5 || creditHours != 6)
{
creditHours = double.Parse(tb_credit.Text);
}
Mehdi is correct, however here's why your code doesn't work.
Let's say the user entered "2", then
if(creditHours != 1 || ...)
{
}
would be true because creditHours is not equal to 1, it is 2. But then let's say that the user enters "9", if(creditHours != 1 || ...) would still be true again because creditHours is not equal to 1 and is instead 9. Hence both valid and invalid values yield the same result. To correct your code you would need if(creditHours == 1 || ...).
Mehdi's code is much simpler, however I like to write;
if(0 <= creditHours && creditHours <= 6)
{
}
think it just reads better.
if (creditHours < 0 || creditHours > 6)
{
throw new Exception("Credit hours can only be between 0 and 6.");
}
Your condition is not right, because if the input number is 7 then then the condition if(creditHours != 1 || ...) will return true.
=> you should validate by this condition if (creditHours > 0 && creditHours < 6)
If user input an invalid number( ex: "abc123xyz" ) then this code will throw exception: creditHours = double.Parse(tb_credit.Text)
=> you should use TryParse to handle invalid number also.
Please check my solution as bellow:
if(!double.TryParse(tb_credit.Text, out var creditHours))
{
throw new Exception("Credit hours should be a numbers between 0 and 6.");
}
if (creditHours > 0 || creditHours < 6)
{
creditHours = double.Parse(tb_credit.Text);
}
throw new Exception("Credit hours should be a numbers between 0 and 6.")

Protecting against Divide by Zero

I'm running into a problem that I think in my mind should work, but keep returning the same Divide by Zero error.
Here is the code I am using that I think should protect against it:
GoalBarValue = Convert.ToInt32(((decimal)CompletedToday /
((decimal)CompletedYesterday) == 0 ? (decimal?)null : (decimal)CompletedYesterday)
* 100); // Divide by zero protection
CompletedToday comes back as 0
CompletedYesterday comes back as 0
Which is perfectly fine and as I expect it should.
The specific error that is being returned is Attempted to divide by zero.
Is something wrong with the way I am trying to protect against it?
"Is something wrong with the way I am trying to protect against it?"
Yes actually, you are dividing by zero! The only way that 0 can be the outcome of your calculation is when CompletedToday is 0. In the other case you divide by 0 and get the nice exception. Why don't you just check whether the divisor is 0 and if not perform the calculation else give it a null :
GoalBarValue = Convert.ToInt32((decimal)CompletedYesterday) == 0 ?
(decimal?)null : (decimal)CompletedYesterday * 100;
Imagine you would check whether you hit your head against a wall by hitting your head against the wall..... it wouldn't be advisable.
EDIT:
If you want 2 assignments of different variables (as you wrote in your comment) then the ? operator is not of much use to you. It allows only 1.
I would suggest to stick to the old fashion way. If you really want the 2 assignments in one line:
if((decimal)CompletedYesterday) == 0)
GoalBarValue = CompletedYesterday = null;
else GoalBarValue = // what ever you want to calculate...
Is this what you want?
if (Convert.ToDecimal(CompletedYesterday) == 0)
{
goalBarValue = null;
}
else
{
goalBarValue = Convert.ToInt32(Convert.ToDecimal(CompletedToday)/Convert.ToDecimal(CompletedYesterday)) * 100;
}
one line version of above code
goalBarValue = Convert.ToDecimal(CompletedYesterday) == 0 ? null : Convert.ToInt32(Convert.ToDecimal(CompletedToday)/Convert.ToDecimal(CompletedYesterday)) * 100;

C# .net - || OR operator not behaving. Seems to be working as AND

This might just be me, but I've been trying to do a do...while loop in c# where the loop will end if either one of two conditions are true.
I'm using the || operator. Google tells me that that is OR, but my loop is only ending when both conditions are true. What am I doing wrong?
Here is a code example:
int sugar=0, salt=0, value=0;
string tLine;
Console.WriteLine("Enter integer values to add to Sugar and Salt.");
Console.WriteLine("The loop should end when either one reaches 10 or more.");
do {
Console.Write("Sugar? =");
tLine = Console.ReadLine();
int.TryParse(tLine, out value);
sugar =sugar+value;
Console.Write("Salt? =");
tLine = Console.ReadLine();
int.TryParse(tLine, out value);
salt =salt+value;
}while ((sugar<10) || (salt<10));
Console.WriteLine("Sugar={0}, Salt={1}", sugar, salt);
Console.ReadKey();
Since the condition in English is:
"The loop should end when either one reaches 10 or more."
Then the condition should be:
do
{
...
}
while (Sugar < 10 && Salt < 10);
You need to use '&&'. Then if either Salt or Sugar becomes >= 10, the result of the && will be false and the loop will therefore terminate.
However, you can use || by inverting the result of the comparison, like so:
while (!(Sugar >= 10 || Salt >= 10))
But that's much harder to read.
Some languages have until, but C# doesn't. If it did, it would look like:
until (Sugar >= 10 || Salt >= 10)
In other words, until (condition) is really the same as while (!condition).
The loop is executed every time the condition is met. So you have to change it to:
while ((sugar<10) && (salt<10))
or
while (!((sugar>=10) || (salt>=10)));
Or you write
while ((sugar<10) && (salt<10));
As long as both are below 10 the while goes on.

Richtextbox Lines.Length == -1

I am trying to number each line in a RichTextBox. I have gotten the number of lines using Lines.Length. If I start typing when it is blank that will turn to 1, but if I press backspace 2-3 times then start typing it returns 0.
(I know pointless) Here is the function that return the number of lines and you can see (my failed attempt) where I tried to compare it with the TextLength to correct the value.
private int LineCount()
{
int textLength = MainIOControl.TextLength;
int lineCount = MainIOControl.Lines.Length - 1;
return (textLength == 0 && lineCount == 0) ? 0 : lineCount;
}
This return the correct value if you just start typing, but not if you press backspace a couple times when it is empty.
Am I simple overlooking something obvious?
Try calculating it yourself instead of using the Lines property:
return MainIOControl.Text.Length - MainIOControl.Text.Replace(Environment.NewLine, string.Empty).Length;
This one may work better for your situation:
private int LineCount()
{
return MainIOControl.Text.Length - MainIOControl.Text.Replace("\n", string.Empty).Length + 1;
}

Difference in seconds LINQ to Entity (DiffSeconds Usage)

I was writing a simple LINQ query which compares rows of a table with itself. Simply put, there are two datagrids on a form, the first one shows some rows and the second one is filled whenever a row is selected in the first grid with the following condition:
Find those rows that have the same code as the selected and their reception time differs less than 30 second (I mean the reception time of shown rows in the second grid must be sooner than reception time of selected row).
I have written the following code:
Call_Log selected = (Call_Log)dataGrid1.SelectedItem;
var subData = from cLog in callLog
where cLog.Check_Create == 1 &&
EntityFunctions.DiffSeconds(selected.ReceptionTime,cLog.ReceptionTime) < 30 &&
selected.CustomerCode == cLog.CustomerCode &&
selected.CalledID == cLog.CalledID &&
selected.ID != cLog.ID
select cLog;
But it returns some rows which differ more than 30 seconds with the selected row. How can I fix this?
Comment:
In the above code, I need to have those rows (cLog) which differ less than 30 seconds from selected row.
Thanks
In case of DiffSeconds return negative value more than 30 seconds, your validation return true.
try compare after taking Math.abs as
Math.Abs(EntityFunctions.DiffSeconds(selected.ReceptionTime,cLog.ReceptionTime)‌​) < 30
Try this.
var subData = from cLog in callLog
let diffInTicks = selected.ReceptionTime.Ticks - cLog.ReceptionTime.Ticks
let thirtySecTicks = new TimeSpan(0, 0, 0, 30, 0).Ticks
where cLog.Check_Create == 1 &&
diffInTicks < thirtySecTicks &&
selected.CustomerCode == cLog.CustomerCode &&
selected.CalledID == cLog.CalledID &&
selected.ID != cLog.ID
select cLog;

Categories

Resources