Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want to know total number of students registered in a particular course whose ID is in "DGVC.Rows[r].Cells[c]".

I've tried this code,it should show 1 in messagebox,as one student is registered to the course, but it gives -1. what shoud i do?

C#
Connection cc = new Connection();
cc.con.Open();

SqlCommand cmdC = new SqlCommand("Select Count(*) from UCK_Scheduler..COURSE_REGISTRATION inner join UCK_Scheduler..STUDENT on COURSE_REGISTRATION.StudentID=STUDENT.StudentID where CourseID='" + DGVC.Rows[r].Cells[c].Value.ToString() + "' ", cc.con);

int cn = cmdC.ExecuteNonQuery();
MessageBox.Show(cn.ToString());
cc.con.Close();
Posted
Updated 9-Oct-13 21:16pm
v2

You're using the ExecuteNonQuery method to select. That is wrong because ExecuteNonQuery is used to insert/update/delete records. In your case, since you're retrieving a single column, you can use ExecuteScalar which retrieves the item found in the first row from the first column.

Further reading here:
ExecuteNonQuery
ExecuteScalar
Comparision between ExecuteNonQuery and ExecuteScalar
 
Share this answer
 
v2
If CourseID is Integer field, then you need to modify the query like below excluding extra single quote.
C#
SqlCommand cmdC = new SqlCommand("Select Count(*) from UCK_Scheduler..COURSE_REGISTRATION inner join UCK_Scheduler..STUDENT on COURSE_REGISTRATION.StudentID=STUDENT.StudentID where CourseID=" + DGVC.Rows[r].Cells[c].Value.ToString() + "", cc.con);


Please debug you code and see what is the value of the query at runtime. Then take the query to SQL Management Studio and run it. You can see the errors, if any.
 
Share this answer
 
you should use ExecuteScalar() not ExecuteNonQuery()

we use EXcuteReader() and ExcuteScalar() for fetch operations and
ExcuteNonQuery() for update and delete operations,
 
Share this answer
 
In sql statement, ExecuteNonQuery is normally used for performing DML operation which allow you to insert, update and delete statement where for latching data from database you have to use ExecuteReader or ExecuteScalar because by using ExecuteReader it's normally used to read data from database tables which return number of record or rows and by using ExecuteScalar it's return the scalar value returns as a one value of first row and first column from database table.


I hope you understand well......!!!
 
Share this answer
 
Yes i should have used ExecuteScalar() instead of ExecuteNonQuery,thank you all.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900