Reputation: 25
I am in trying to create a form that converts decimals to a letter grade. The issue is that the letterGrade does not exist in that current context of the method but how do I essentially get it to "return". I am new to C#. I will appreciate any help I can get.
private void txtNumberGrade_TextChanged(object sender, EventArgs e)
{
txtNumberGrade.Focus();
}
private void txtLetterGrade_TextChanged(object sender, EventArgs e)
{
//error at this line below
txtLetterGrade.Text = letterGrade;
//error at this line above
}
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal score = Convert.ToDecimal(txtNumberGrade.Text);
string letterGrade = "";
if (score >= 90)
{
letterGrade = "A";
}
else if (score >= 80)
{
letterGrade = "B";
}
else if (score >= 70)
{
letterGrade = "C";
}
else if (score >= 60)
{
letterGrade = "D";
}
else if (score >= 0)
{
letterGrade = "F";
}
else {
letterGrade = "Z";
}
}
}
Upvotes: 1
Views: 212
Reputation: 8004
What you could do is create a function to return the grade you need. Below I am using the Decimal.TryParse Method which converts the string representation of a number to its Decimal equivalent and a return value indicates whether the conversion succeeded or failed. If it did succeed, then score
would have this value.
private static string GetGrade(string decGrade)
{
if (decimal.TryParse(decGrade, out decimal score))
{
if (score >= 90)
{
return "A";
}
else if (score >= 80)
{
return "B";
}
else if (score >= 70)
{
return "C";
}
else if (score >= 60)
{
return "D";
}
else if (score >= 0)
{
return "F";
}
else
{
return "Z";
}
}
else { return "NA"; }
}
Now you can call this in the TextChanged
event as such:
private void txtNumberGrade_TextChanged(object sender, EventArgs e)
{
txtLetterGrade.Text = GetGrade(txtNumberGrade.Text);
}
References:
Decimal.TryParse Method - https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryparse?view=netcore-3.1
Upvotes: 1