Ray Zane
Ray Zane

Reputation: 246

How do I fix this error? "InvalidCastException was unhandled"

I'm in an intro level programming class and I have to make a grade calculator. There are 2 homework grades, 2 quiz grades, and one final grade. Homeworks are worth 25%, quizzes are worth 35%, and the final is worth 40%.

I want to be able to enter the students grades and name and when I click the 'Calculate' button, have the course grade and student name at the bottom in a label.

It seems I am having some sort of problem when I convert. I have tried using integers, and I get the same problem. I could really use some help please!

Here is the code for the button click:

    private void btnCalculate_Click(object sender, RoutedEventArgs e)
    {
        //Defining, converting, and assigning variables
        string studentName = Convert.ToString(tbName);
        double hw1 = Convert.ToDouble(tbHW1);
        double hw2 = Convert.ToDouble(tbHW2);
        double quiz1 = Convert.ToDouble(tbQuiz1);
        double quiz2 = Convert.ToDouble(tbQuiz2);
        double final = Convert.ToDouble(tbFinal);
        const double HWWeight = 0.25;
        const double quizWeight = 0.35;
        const double finalWeight = 0.40;
        double studentGrade;

        //Grade Calculation
        studentGrade = ((hw1 + hw2) * HWWeight) + ((quiz1 + quiz2) * quizWeight) + (final * finalWeight);

        //Display results
        lblLeftResult.Content = studentName;
        lblRightResult.Content = studentGrade;          

    }

Upvotes: 0

Views: 5155

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

I assume tbName etc are TextBoxes... in which case you probably want something like:

string studentName = tbName.Text;
double hw1 = double.Parse(tbHW1.Text);
// etc

In other words, don't try to convert the text box itself - convert the Text of the text box.

Upvotes: 9

Related Questions