Skip to content
Advertisement

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;

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement