C# problem calculating average from 2 columns,total comments

March 14, 2013 at 13:17:17
Specs: Windows Vista, Intel Core2 Quad 6600
Hi, I am trying to retrieve data from a database to display some summary information about the total number records, the average of 2 different columns and numbers of records that have comments under the comment column. I can get the total number of records. I get the wrong total for number of comments. For the average ratings, I get the error Specified cast is not valid. I'm sorry but I am a newbie at this.


string vsql2 = ("SELECT avg(TeacherRating) FROM tblCourseEvals");
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Connection = vcon;
cmd2.CommandText = vsql2;
cmd2.CommandType = CommandType.Text;

try
{
int EvalsTotal2 = (int)cmd2.ExecuteScalar();
lbAvgRateTeachers.Text = EvalsTotal2.ToString();
}
catch (Exception ex)
{
MessageBox.Show("The teacher data was not calculated successfully! " + ex.Message);
}


string vsql3 = ("SELECT avg(CourseRating) FROM tblCourseEvals");
OleDbCommand cmd3 = new OleDbCommand();
cmd3.Connection = vcon;
cmd3.CommandText = vsql3;
cmd3.CommandType = CommandType.Text;

try
{
int EvalsTotal3 = (int)cmd3.ExecuteScalar();
lbAvgRateCourses.Text = EvalsTotal3.ToString();
}
catch (Exception ex)
{
MessageBox.Show("The course data was not calculated successfully! " + ex.Message);
}


string vsql4 = ("SELECT count(Comments) FROM tblCourseEvals");
OleDbCommand cmd4 = new OleDbCommand();
cmd4.Connection = vcon;
cmd4.CommandText = vsql4;
cmd4.CommandType = CommandType.Text;
try
{
int EvalsTotal4 = (Int32)cmd.ExecuteScalar();
lbNumEvalComm.Text = EvalsTotal4.ToString();
}
catch (Exception ex)
{
MessageBox.Show("The number of comments was not calculated successfully! " + ex.Message);
}

vcon.Close();


See More: C# problem calculating average from 2 columns,total comments

Report •

#1
March 14, 2013 at 15:47:11
I get the wrong total for number of comments.
Define "wrong"

For the average ratings, I get the error Specified cast is not valid.
Check what your ExecuteScalar() is returning. C# is saying it isn't a number.

How To Ask Questions The Smart Way


Report •

#2
March 15, 2013 at 09:27:46
I have 2 records in a database. Only one has data under the Comments column. It return 2 instead of 1. How do I check what Visual C# is returning?

Report •

#3
March 15, 2013 at 18:02:22
Only one has data under the Comments column. It return 2 instead of 1.
Does the non-Comments record have null in its 'Comments' column, or just an empty string?

How do I check what Visual C# is returning?
I'm tempted to tell you to just call ToString() on it without trying to cast it first, but I suspect you'd be better served with a program like Toad, as that'll let you visualize your SQL queries before putting them into your program.

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question