Filling a Binding Source with a Data Reader

Another opportunity that opens up with the binding source that wasn't really an option before in Windows Forms is the ability to bind controls (indirectly) to data coming from a data reader. If you execute a data reader through a command object, you can set a binding source's DataSource property to that data reader. The binding source will iterate through the data reader's contents and use it to quickly populate the binding source's List collection. Then, as long as you execute the data reader using the

CommandBehavior.CloseConnection flag, the connection will close and release back to the connection pool. Or you can close it explicitly or by disposing of the connection. See Appendix D if you are unfamiliar with data readers.

The code in Listing 4.5 shows using a data reader for binding. First the grid that thfiindingSource is bound to has its AutoGenerateColumns property set to true in the constructor. This is required any time you will dynamically provide data to a DataGridView control without setting up its columns ahead of time. In theForm.Load event handler, after executing the reader, the code sets the binding source's data source property to the reader, which causes the binding source to iterate through all the items in the reader and add them to the internal List maintained by the binding source. In this case, the items added to thdJst of the binding source are instances of the DbDataRecord class from the System.Data.Common namespace. These objects have enough schema information embedded that it's easy for the DataGridView or other controls to use reflection to extract the column schema information just like it would for a Data Table.

+1 0

Responses

  • bildad
    Can I bind a datareader to bindingsource?
    7 years ago
  • Daisy
    How to update records in bindingsource datagridview datareader vb.net?
    7 years ago

Post a comment