How to: Bind the Windows Forms DataGrid Control to a Data Source
The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.
The Windows Forms DataGrid control is specifically designed to display information from a data source. You bind the control at run time by calling the SetDataBinding method. Although you can display data from a variety of data sources, the most typical sources are datasets and data views.
To data-bind the DataGrid control programmatically
Write code to fill the dataset.
If the data source is a dataset or a data view based on a dataset table, add code to the form to fill the dataset.
The exact code you use depends on where the dataset is getting data. If the dataset is being populated directly from a database, you typically call theFill method of a data adapter, as in the following example, which populates a dataset calledDsCategories1:
If the dataset is being filled from an XML Web service, you typically create an instance of the service in your code and then call one of its methods to return a dataset. You then merge the dataset from the XML Web service into your local dataset. The following example shows how you can create an instance of an XML Web service calledCategoriesService, call itsGetCategories method, and merge the resulting dataset into a local dataset calledDsCategories1:
If you are binding the grid for the first time, you can set the control's DataSource and DataMember properties. However, you cannot reset these properties once they have been set. Therefore, it is recommended that you always use the SetDataBinding method.
The following example shows how you can programmatically bind to the Customers table in a dataset calledDsCustomers1:
If the Customers table is the only table in the dataset, you could alternatively bind the grid this way:
(Optional) Add the appropriate table styles and column styles to the grid. If there are no table styles, you will see the table, but with minimal formatting and with all columns visible.