mimickd mimickd - 1 year ago 142
SQL Question

SqlCommand only returns one row

Trying to only return the first few number of rows because my database was too big, however when I was testing my SQL, I did a

select *
and was only returned the first row.

SqlCommand sqlCmd = new SqlCommand();
SqlDataReader reader;

sqlCmd.CommandText = "SELECT * FROM Log";
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Connection = myConnection;


reader = sqlCmd.ExecuteReader();

Log logs = null;

while (reader.Read())
logs = new Log();
logs.Id = Convert.ToInt32(reader.GetValue(0));

return logs;

What is wrong with my solution?

Answer Source

In your loop you constantly re-create the instance of the variable logs thus overwriting the previous one and ending with the value of the last record returned by your query. You need a List<Log>

    List<Log> logs = new List<Log>();
    while (reader.Read())
        Log current = new Log();
        logs.Id = Convert.ToInt32(reader.GetValue(0));

You can use this list as datasource for a grid or just keep it for your future references...

    foreach(Log log in logs)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download