Someone emailed recently and asked "Using MxDatagrid [the data grid control in Web Matrix], how can I easily get the number of rows returned from the issued select statement?" The guy was paging in the grid, and wanted to do an n of m display, where m was the total number of records that the query would return.
Perhaps surprisingly, this information does not appear to be directly exposed by the data source controls. I say surprisingly because if anyone would know how many records are in the current query, it's the data souce control. In Visual Web Developer, for example, there is no direct way to get something like the SqlDataSource control to tell you how many records its most recently executed query returned.
Slighlty oddly, Web Matrix, which introduced proto-versions of the data source controls, actually did seem to have a way to do this, albeit one that doesn't seem like it was directly designed for it. We stumbled on a way to get the SqlDataSourceControl (this is Web Matrix, remember) to cough up the info using this code:
Dim itemCount As Integer = 0Needless to say, this is a hack. It relies on the heavily underdocumented GetDataSource method, and who knows what that's actually for? There isn't much in the way of Web Matrix documentation. However, my correspondent was happy to report that it did work for him.
Dim dataSourceItems As IEnumerable = SqlDataSourceControl1.GetDataSource("")
Dim o As Object
For Each o In dataSourceItems
itemCount += 1
I asked around about this issue with some internal folks. One of the people who'd worked on the data source controls for ASP.NET 2.0 explained that when they were designing the controls, the intention was to expose only the APIs that data-bound controls would need to do their binding. They didn't think of them in terms of page developers invoking the data source control APIs directly -- in effect, using them as a declarative query object. (An exception would be the ObjectDataSource control, since after all you control what it exposes.)
Of course, getting a total count is perfectly possible -- you just do an ExecuteScalar with the query
Select Count(*) and using the same criteria that the data source control is using. But that's a second query against the same data source.
AFAIK, that's the canonical way to find out how many total records your data source control is returning in a query. If I find out more (or wake up and start thinking straight), I'll follow up.