Data Access in .NET using C#: Part 1 - The DataReader Object (Page 3 of 4 )
We can use a DataReader object to read data from a database. A DataReader object is effectively a forward-only collection of records from your data source. The problem is, you can't go back because the recording is forward only. A DataReader cannot be used to write or modify data. When creating a DataReader, we first create a command object from the connection object and then initialize this object using CommandText property:
The DataReader object exposes a Read() method. The Read() method automatically points to the next row in the database table that we are working with. When there are no more rows, the Read() method will return false. In the code above we are using a simple while loop to check the table data.
In the body of the while loop, the Read() method returns and adds the email field from the table into our list box control. Press Ctrl + F5 for build solutions and execute our application without debugging.
Click on the button to connect to the database and retrieve the email address. The email address from our database table should appear in the list box on our form.
Finally, always call the Close() method when you are finished with the database. This will free up the memory used previously by the database objects. The garbage collector will do this for us automatically, but in its own time. In the meantime, valuable resources are being taking up. Until the garbage collector comes around and removes the connections -- freeing resources -- the database connection will still be open, which is a waste of resources and a bad programming practice.