2013-03-05 40 views
-1

我正在編寫C#代碼,並且在點擊提交按鈕時遇到了問題,並選擇了複選框答案的幾種不同組合,但它們沒有正確更新「正確」或「不正確」。如何將代碼調整到只有Answer2和Answer3被選中,只有「Correct」標籤會顯示?即使選擇了正確答案中的一個錯誤答案,該答案也會顯示「不正確」。如何在提交互斥複選框後更新標籤?

if (Answer2.Checked && Answer3.Checked == true) 
    { 
     lblQuestionResult4.ForeColor = System.Drawing.Color.Green; 
     lblQuestionResult4.Text = "Correct"; 
    } 
    else 
    { 
     if (Answer1.Checked && Answer4.Checked == true) 
     { 
      lblQuestionResult4.ForeColor = System.Drawing.Color.Red; 
      lblQuestionResult4.Text = "Incorrect"; 
     } 

回答

0

這裏有一種方法。在你的代碼片段中有條件不明的情況。這段代碼避免了假設最差的情況,並且只有在出現正確的情況下才設置這些值(即,選中了答案2 & 3,其餘所有內容都未選中)。

var color = System.Drawing.Color.Red; //assume incorrect answer 
var label = "Incorrect"; 

if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked) 
{ 
    //only the 2 correct answers have been checked 
    color = System.Drawing.Color.Green; 
    label = "Correct"; 
} 

// set the controls 
lblQuestionResult4.ForeColor = color; 
lblQuestionResult4.Text = label;