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 the
Fillmethod of a data adapter, as in the following example, which populates a dataset called
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 called
CategoriesService, call its
GetCategoriesmethod, and merge the resulting dataset into a local dataset called
Dim ws As New MyProject.localhost.CategoriesService() ws.Credentials = System.Net.CredentialCache.DefaultCredentials DsCategories1.Merge(ws.GetCategories())
MyProject.localhost.CategoriesService ws = new MyProject.localhost.CategoriesService(); ws.Credentials = System.Net.CredentialCache.DefaultCredentials; DsCategories1.Merge(ws.GetCategories());
MyProject::localhost::CategoriesService^ ws = new MyProject::localhost::CategoriesService(); ws->Credentials = System::Net::CredentialCache::DefaultCredentials; dsCategories1->Merge(ws->GetCategories());
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 called
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.