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?

Terry
  • 989
  • 8
  • 29
Kate
  • 372
  • 2
  • 11
  • 24
  • 1
    `if (((CheckBox)ListView2.Items[i].FindControl("UcastCheckBox")).Checked=false || a > 0)` You're setting `Checked = false` instead of checking `Checked == false` – Nolonar Jun 19 '13 at 11:08

4 Answers4

3

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.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
1

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>");
}
gzaxx
  • 17,312
  • 2
  • 36
  • 54
1

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)
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
1

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.

Community
  • 1
  • 1
Alex
  • 23,004
  • 4
  • 39
  • 73