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.
Related
I really don't why it doesn't working. (it should check if number is binary)
why the operators doesn't apply right?
using System;
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(IsBin(100));
Console.WriteLine(IsBin(10011012));
Console.WriteLine(IsBin(10911010));
}
public static bool IsBin(long num)
{
while (num > 0)
{
if ((num % 10) != 1 || (num % 10) != 0)
{
return false;
}
num /= 10;
}
return true;
}
}
At least one expression on each side of the || is always true. So the result of the expression using || is always true.
You can do your check in one expression using a ! (not), but this will make your code less readable, so I suggest store the result in a temporary variable to improve readability.
You could be using:
var isZeroOrOne = (num % 10) == 1 || (num % 10) == 0)
if (!isZeroOrOne)
{
return false;
}
num /= 10;
Too Long, Won't Read: Use && instead of || in your if statement.
And for those, who wants to know why:
OR operator(||) returns true when at least one side is true. So 100%10=0 and 0!=1 is true so the whole or statement will return true and program will jump into your if statement.
AND operator(&&) returnstrue only when both sides are true. 0!=1 is true but 0!=0 is false so the && operator will return false and your if will not be executed.
Is it clear?
I'm trying to understand how it is possible to put condition inside condition itself.
for example, below I'm showing wrong unreal code, but clear to understand what I'm asking for without extra words:
if (a == 1 && if (b == 1) { c >= 5 })
{
/// process
}
So condition c >= 5 must be taken into the account for process only in case if b == 1 which must be exist inside one statement without using of separate function with separate conditions or as condition after condition.
Question is how take part of condition into the account inside the condition only in case if some value is true and avoid it if false and read only a == 1.
EDIT based on answer below:
int a = 1;
int b = 0;
int c = 6;
if (a == 1 && (b != 0 || c >= 5))
{
Console.WriteLine("yes");
if (c > 5)
{
Console.WriteLine("taken into the account");
}
}
else
{
Console.WriteLine("no");
}
in both cases int b = 1; and int b = 0; result is:
yes
taken into the account
desired result:
in case of int b = 1; :
yes
taken into the account
and in case of int b = 0;:
yes
if (a == 1 && (b != 1 || c >= 5 ))
Here, c >= 5 will only be evaluated when b==1.
In c# && is a short circuiting operation so b==1 will not be evaluated if a==1 does not evaluate to true.
Let's say I have a 5 textbox and 1 combobox and I make the value inputted pass to a variable like this
name = textboxName.Text.ToString();
address = txtboxAddress.Text.ToString();
destination = comboboxDestination.Text.ToString(); // combobox
position = txtboxPosition.Text.ToString();
station = txtboxStation.Text.ToString();
purpose = richtxtboxPurpose.Text.ToString();
Then I wanted to check if their value is null or just blank space.
int switchCase = 0;
if (string.IsNullOrWhiteSpace(name) && name.Length > 0 ||
string.IsNullOrWhiteSpace(address) && address.Length > 0 ||
string.IsNullOrWhiteSpace(destination) && destination.Length > 0 ||
string.IsNullOrWhiteSpace(position) && position.Length > 0 ||
string.IsNullOrWhiteSpace(station) && station.Length > 0 ||
string.IsNullOrWhiteSpace(purpose) && purpose.Length > 0
)
{
switchCase = 2;
}
else
{
switchCase = 1;
}
then for my trap is this
switch (switchCase)
{
case 1:
MessageBox.Show("Profile created!");
break;
case 2:
MessageBox.Show("Please complete the form to procede.");
break;
}
The problem is if I just load up the page and didnt typed anything it is going to the case 1 which means that all of my textboxes and combobox have a value. Then if I key in just space in all of the textboxes it reads the condition and go to case 2 what is going on?
EDIT:
My first code is like this and it is working well
if (name == "" || address == "" || destination == "" || position == "" || station == "" || purpose == "")
Although it is prone to the blank space.
Your code here:
string.IsNullOrWhiteSpace(name) && name.Length > 0 is checking if the string is empty, entirely whitespace, or null. Then you add a length check, effectively changing it into 'only accept strings which contain whitespace, but not blank.
Removing the length check should work as expected.
In addition, you can clean up the code a bit, to reduce repetitiveness:
if (new[] { name, address, destination, position, station, purpose }
.Any(str => string.IsNullOrEmpty(str)))
{
....
}
How to check if there is an element at the specific index in a list, like
Product[i]
Is it there or not? How to write this check?
If i is the index you want to have, check the Count:
if (i >= 0 && (list.Count - 1) >= i)
{
// okay, the item is there
}
If talking about nullable types, you could also check if the item on that index isn't null:
if (i >= 0 && (list.Count - 1) >= i && list[i] != null)
{
// okay, the item is there, and it has a value
}
try like this
if (Product.Contains(yourItem))
int Index = Array.IndexOf(Product, yourItem);
if you want to check that the index is exist in that particular array then you can just check the length of that array.
if (i < Product.Length && i > -1)
//yes it has
return (Product.Count() -1) <= i;
or if you're feeling hackish:
try { var x = Product[i]; return true; } catch(ArrayIndexOutOfBoundException) { return false; }
or
Product.Skip(i).Any()
or...
I want to write a check for some conditions without having to use try/catch and I want to avoid the possibilities of getting Index Out of Range errors
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
So the problem I am facing is that in the second check I need to see whether I have one Item that is not empty. However, If I don't have Element[1], I get the Index Out of Range exception. The problem is that there could be 2 Elements and one(or both) of them may have empty Object arrays. The code will have to be executed only if one of thos Item strings is not empty.
Hopefully, I explained it well. How do I go about avoiding getting that exception under any condition?
Alright, you need some better null checking and some more cautious code here.
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
is just unacceptable.
First, let's null check
if (array != null)
{
if (array.Element != null)
for simplicity, you could use &&
if (array != null && array.Element != null)
then, inside that if, we use a for loop (since you're stuck on arrays) and null check it
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
then, since you have nested arrays, we loop again. This is called a nested loop, and it's generally bad practice, I'll show you why it works in a second.
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
Now, with all of that ugly nested loopyness, we've found out that your Item is not null.
On top of that, you have access to ALL of the potential values here, and can group them as you like. Here's how I would put the whole thing together for simplification.
List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
for (int i = 0; i < array.Element.length; ++i)
{
//bool found = false;
if (array.Element[i] != null && array.Element[i].Object != null)
{
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
arrayValues.Add(array.Element[i].Object[o].Item);
//if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
//found = true;
//break;
}
}
}
//if (found)
// break;
}
}
if (arrayValues.Count > 0)
{
//do stuff with arrayValues
}
Could use a LINQ method ElementAtOrDefault(index)
so if the element is not found it will be null.
var currentElem = Elems.ElementAtOrDefault(i);
if(currentElem != null)
// do something
else
// do something
Could you do something like:
if(array.Element[0] != null || array.Element[1] != null){
//execute code
}
Your code is probably subject to refactor.
I assume it can work this way:
var obj = array.Element.FirstOrDefault(x => x.Object.Length > 0);
if (obj != null)
{
if (obj.Object[0].Item.Length != 0)
{
// do whatever is necessary
}
}
I think you can put your check in right before your first if Check.
if (array.Length > 1 && array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
This should just short-circuit out if your array doesn't have both Elements.
Place both tests together using the short-circuit && so that the second test doesn't occur if the first fails:
object element0 = array.Element[0].Object;
object element1 = array.Element[1].Object;
// Ensure at least one Object array has a non-empty value.
if ((element0.Length > 0 && !string.IsNullOrEmpty((string)element0.Object[0].Item))
|| (element1.Length > 0 && !string.IsNullOrEmpty((string)element1.Object[1].Item)))
{
// ...
}
I am presuming it is Object[1] causing the exception--you weren't clear on that. If it is Element[1] that causes the exception (or both), then you need to pre-test the length of the array:
if ((array.Element[0].Length != 0 && HasValue(array.Element[0].Object))
|| (array.Element[1].Length > 1 && HasValue(array.Element[1].Object)))
{
// ...
}
// <summary>
// Returns true if the specified string array contains a non-empty value at
// the specified index.
// </summary>
private bool HasValue(System.Array array, int index)
{
return array.Length > index &&
!string.IsNullOrEmpty((string)array.Object[index].Item);
}
for (long i = 0; i <= (output3.Length); i++)
{
output1.WriteByte(output3[i]); -----> index out of range exception correct it
output1.WriteByte(output3rx[i]);
}