user2057071
user2057071

Reputation: 1

How to get numbers of rows in sql query?

    string query = q;
    SqlCommand queryCommand = new SqlCommand(query, Connection);
    SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
    DataTable dataTable = new DataTable();
    dataTable.Load(queryCommandReader);
    List<string> rowText = new List<string>();

    for (int i = 0; i < 4; i++)
    {
        foreach (DataColumn columns in dataTable.Columns)
        {
            rowText.Add(dataTable.Rows[i][columns.ColumnName] + "");
        }
    }

in this example I get 4 rows from database the condition in for loop i < 4 I wanna get really numbers of rows not just 4

Upvotes: 0

Views: 1160

Answers (2)

Oliver
Oliver

Reputation: 45071

In your specific example simple replace the the 4 by dataTable.Rows.Count so that you get:

for(int i = 0; i < dataTable.Rows.Count; i++)
{
    // ...
}

Or switch to foreach and use the answer of Gaby.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195962

Use foreach for the rows as well
See http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

foreach(DataRow row in dataTable.Rows)
{
    foreach (DataColumn column in dataTable.Columns)
    {
        rowText.Add( row[column] );
    }
}

Upvotes: 2

Related Questions