You should use ExecuteScalar() , not ExecuteNonQuery() , because you are retrieving the value.
count = Convert.ToInt16(cmd.ExecuteScalar()) MsgBox(count.ToString())
For proper coding
- use
using to properly delete an object - use
try-catch block to handle exceptions correctly
Code example:
Dim connStr As String = "connection string here" Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1" Using conn As New SqlConnection(connStr) Using comm As New SqlCommand() With comm .Connection = conn .CommandText = query .CommandType = CommandType.Text End With Try Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar()) MsgBox(count.ToString()) Catch(ex As SqlException) ' put your exception here ' End Try End Using End Using
source share