Count records using ExecuteScalar in ASP.NET

April 15, 2008

After much research, it was incredibly annoying to try and find a decent script on how to count records from a database using ASP.NET (via VB). I gathered from different resources and wrote a simple script to get the job done. I decided to post it in case anyone is going through the same headache I just went through.

You can put this in a function and return the record count easily. The following is a simple example of how to count records using ExcuteScalar in ASP.NET.

Dim SQLString As String = “SELECT Count(columnName) FROM tableName
yourDBConnection As New SqlConnection()
yourDBConnection.ConnectionString = yourConnectionString

cmd As New SqlCommand()
Dim recCount As Integer


cmd.Connection = yourDBConnection
cmd.CommandText = SQLString
recCount = Integer.Parse(cmd.ExecuteScalar().ToString)


‘Return recCount

Happy programming!



  1. Thx ..was a real help.:)

  2. I also had a real headache trying to figure this out. There’s another easy way of doing it at http://www.dinowebs.net/?p=42

    This uses the Data Source control’s Data.DataView property.

  3. Thanks! You just help me achieve what I wanted.


  5. Thanks a lot……………..

  6. tnx very much no more heartache

  7. Unquestionably believe that which you said. Your favorite justification seemed to be on the net the simplest thing to be aware of.
    I say to you, I definitely get irked while people think about worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people could take a signal. Will probably be back to get more. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: