简体   繁体   English

如果我的if语句不起作用,为什么会起作用?

[英]why does my if statement work if it shouldnt?

i working in asp.net, i am not very familiar with html and c# since the prof really doesnt go over much until it comes up in class.. i do understand it is very similar to java which i am quite familiar with so im not sure what my error is 我在asp.net中工作,我对html和c#不太熟悉,因为教授在上课之前确实不会花费太多。确定我的错误是

i have an if statement for a click event to check the selected index of the checkbox list to make sure the right answers are chosen. 我有一个click事件的if语句,以检查复选框列表的选定索引,以确保选择了正确的答案。 it works somewhat right but for some reason whenever the first index is selected it makes it right which i dont understand. 它的工作原理是正确的,但是由于某种原因,无论何时选择第一个索引,它都会使它正确,我不理解。 so really my issue is the selection of the first index causing some sort of issue with the if statement 所以实际上我的问题是选择第一个索引导致if语句出现某种问题

here is my code for the event handler of the button.. 这是我的按钮事件处理程序的代码。

if (DropDownList1.SelectedIndex.Equals(1)) { 
    LabelResult1.Text = "Question 1 Correct"; 
}
else { 
    LabelResult1.Text = "Question 1 Incorrect"; 
}

if (RadioButtonList1.SelectedIndex.Equals(1)) { 
    LabelResult2.Text = "Question 2 Correct";
}
else { 
    LabelResult2.Text = "Question 2 Incorrect"; 
}

if (CheckBoxList1.SelectedIndex.Equals(0&2&3)) { 
    LabelResult3.Text = "Question 3 Correct"; 
}
else { 
    LabelResult3.Text = "Question 3 Incorrect"; 
}

//write if statement to create image for fireworks
if(DropDownList1.SelectedIndex.Equals(1)&&RadioButtonList1.SelectedIndex.Equals(1)&&CheckBoxList1.SelectedIndex.Equals(0 & 2 & 3)) {
    ImageFireworks.ImageUrl = "Images/giphy.gif";
}

i also have it so the gif appears if all questions are answered correctly. 我也有它,所以如果所有问题都正确回答,就会出现gif。 same the if statement, same issue is happening with it that anytime the 0 index of the checkbox is selected, they appear 与if语句相同,每次选择复选框的0索引时,都会出现相同的问题

CheckBoxList1.SelectedIndex.Equals(0&2&3) will evaluate to true for a index = 0 because 0&2&3 is zero. CheckBoxList1.SelectedIndex.Equals(0&2&3)对于索引= 0的计算结果为true,因为0&2&3为零。 This is because in c# the & operator is a bitwise AND. 这是因为在c#中, & operator是按位与。

  • 0 = b00000000 0 = b00000000
  • 2 = b00000010 2 = b00000010
  • 3 = b00000011 3 = b00000011

These three combined with an binary AND operator (like you did) will result in 0. 这三个与二进制AND运算符结合在一起(就像您所做的那样)将得出0。

Single & is the bitwise AND operator so 0 & 2 & 3 evaluates to 0 which makes your expression work like SelectedIndex.Equals(0) . Single &是按位AND运算符,因此0 & 2 & 3计算结果为0,这使您的表达式像SelectedIndex.Equals(0)一样工作。 In order to check for multiple selected items, you have to check the .Selected property of each item like: 为了检查多个选定项目,您必须检查每个项目的.Selected属性,例如:

CheckBoxList1.Items[0].Selected && CheckBoxList1.Items[2].Selected && CheckBoxList1.Items[3].Selected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM