[英]why does my if statement work if it shouldnt?
我在asp.net中工作,我對html和c#不太熟悉,因為教授在上課之前確實不會花費太多。確定我的錯誤是
我有一個click事件的if語句,以檢查復選框列表的選定索引,以確保選擇了正確的答案。 它的工作原理是正確的,但是由於某種原因,無論何時選擇第一個索引,它都會使它正確,我不理解。 所以實際上我的問題是選擇第一個索引導致if語句出現某種問題
這是我的按鈕事件處理程序的代碼。
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";
}
我也有它,所以如果所有問題都正確回答,就會出現gif。 與if語句相同,每次選擇復選框的0索引時,都會出現相同的問題
CheckBoxList1.SelectedIndex.Equals(0&2&3)
對於索引= 0的計算結果為true,因為0&2&3
為零。 這是因為在c#中, & operator
是按位與。
這三個與二進制AND運算符結合在一起(就像您所做的那樣)將得出0。
Single &
是按位AND運算符,因此0 & 2 & 3
計算結果為0,這使您的表達式像SelectedIndex.Equals(0)
一樣工作。 為了檢查多個選定項目,您必須檢查每個項目的.Selected
屬性,例如:
CheckBoxList1.Items[0].Selected && CheckBoxList1.Items[2].Selected && CheckBoxList1.Items[3].Selected
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.