views:

394

answers:

2

Hello,

I would like to know how can I get record count of a query with C#.

Here is the code that I use..

    MySqlDataReader recordset = null;
    query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
    recordset = query.ExecuteReader();


    while (recordset.Read())
    {
        result.Add(recordset["type_ID"].ToString());

    }
    return result;
A: 

You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.

Mark Byers
unfortunetely I have to get row count before the while() loop...
she hates me
@she hates me: Just curious, but why why would you need the row count before the loop?
Pandincus
@she hates me: If the result set is small, iterate through it once and store the rows in a list, then get the count, then iterate through the stored list to get all the rows again. The second time you iterate through you know how many elements you have and you can do whatever you were doing that needs the count here.
Mark Byers
+1  A: 

You could run another query first to get the count :

query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);

but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.

Mongus Pong