2

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;

myConnection.Open();

reader = sqlCmd.ExecuteReader();

Log logs = null;

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

return logs;
myConnection.Close();

What is wrong with my solution?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mimickd
  • 77
  • 9

1 Answers1

9

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));
        logs.Add(current);
    }

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

    foreach(Log log in logs)
       MessageBox.Show(log.Id);
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Steve
  • 213,761
  • 22
  • 232
  • 286