I am working on a school program im stuck at a point where I have a button and i want it to get the Highest grade of a certain Exam , i used the below code but didnt work i want the button to return a messagebox with the student name and exam name and grade which is the highest one, and to specify which exam im using a combobox with the list of exam names , noting that im using SQL management studio for database information and in the screenshot is the form design
Code:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) AS Expr1, ExamName, StudentName, MAX(Grade) AS Expr2 FROM Grades WHERE ExamName = @ex GROUP BY ExamName, StudentName, Grade ORDER BY Grade DESC", conn);
cmd.Parameters.AddWithValue("@ex", cbExam.SelectedValue.ToString());
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
string outputMessage = "";
try
{
while (rd.Read())
{
outputMessage += rd.GetValue(2) + "- " + rd.GetValue(3) + "\n";
}
}
catch (Exception x)
{
MessageBox.Show(x.Message.ToString());
}
rd.Close();
conn.Close();
MessageBox.Show(outputMessage);
At the moment you're only passing in the exam name for a parameter. So the query will return the max grade for that exam - but for ALL students. So what you're seeing is probably just the first record, which would be teh student with the highest grade for that exam (since you have an order by on it). If you only want the highest grade for one student for one exam, then you need to either include the name in the where clause, in addition to the exam, or loop through the results to find the name you're looking for.
It's all very similar to my code learning, I studied html and javascript and it took me quite a long time to figure out some of the functions. I was never very good at programming so it was hard for me at first, but after going through the classes, I gradually mastered those markup languages. So, I wish you success! Sometimes it can seem overwhelmingly difficult, but the main thing is not to give up. Then I realized that I wanted to work in another field so I went to asa college miami florida for a second degree and studied medicine, which I always liked much more than programming. But my knowledge of code came in handy anyway.
Last edited by kalonmarko; Jul 28th, 2022 at 09:28 AM.