我是C#的新手,我遇到了TextBox驗證等級字母(A,B,C,D,F)的問題。現在,下面的代碼將執行if語句,而不是else語句,因爲如果我輸入與其條件完全匹配的等級字母,即使是下單元,然後單擊「確定」按鈕後上單元,也會如此。當我輸入一個正確的成績信時,它應該跳過if並繼續到else語句,但有些錯誤我沒有看到。如何在C#中正確驗證TextBox?
private void Button_Click(object sender, RoutedEventArgs e)
{
//automatically convert gradeLetter inputs to uppercase
gradeLetter.Text = gradeLetter.Text.ToUpper();
//check if gradeLetter entered is valid
if (!string.IsNullOrWhiteSpace(gradeLetter.Text) || gradeLetter.Text != "A" || gradeLetter.Text != "B" || gradeLetter.Text != "C" || gradeLetter.Text != "D" || gradeLetter.Text != "F")
{
MessageBox.Show("Invalid grade letter or has an empty textbox!", "Caution!", MessageBoxButton.OK);
}
else
{
// switch statement to determine which 'gradeLetter' is being used
// and assign numerical numbers to 'gpa' to then be calculated.
switch (gradeLetter.Text)
{
case "A": gradeW = 4.0;
break;
case "B": gradeW = 3.0;
break;
case "C": gradeW = 2.0;
break;
case "D": gradeW = 1.0;
break;
case "F": gradeW = 0.0;
break;
default: // do nothing
break;
}
double result = (GPA += gradeW); //add to the gpa
gCounter++; // increment the gpa entered
result /= gCounter; // divide by the number of gpa entered
result = Math.Round(result, 2, MidpointRounding.AwayFromZero); //round the result to two decimal places
gpa.Text = result.ToString(); //convert result from int to string and display in 'gpa' TextBlock
//append the input grade letters to 'gradeEntered' TextBlock
gradeEntered.Text += gradeLetter.Text + System.Environment.NewLine;
}
}
你有設置一個斷點,並通過您的條件踩看到* *爲什麼它的表現出乎意料? –
我也是新來Visual Studio 2013,我不知道如何調試,但向我展示如何將不勝感激。我一定會利用它。 – TheAmazingKnight
A [視頻解說可能是您獲得想法的最佳方式](http://www.youtube.com/watch?v=C0vDKXIq_9A) - *(我沒有看到這個,但它是第一個結果我搜索了「在Visual Studio中調試」,應該足夠了* –