A common requirement and question that is very easy to solve with the DataGrid is the need to have a column or columns in a grid that contain a drop down list of lookup values from a related table. For example, in Northwind, we have the Products table with a foreign key column SupplierID that relates the to Suppliers table. The values in the Suppliers table could be treated as a list of lookup values for editing the supplier associated with a product:
When a supplier is selected from the drop down list, it should set the SupplierID column value for that row in the products table. This is very easy to achieve through the Windows Forms designer and the smart tag for a DataGridView control.
Do the following to try it out:
- Create a Windows Forms Project.
- Add a data source to a data set that contains Products and Suppliers tables from the Northwind database. This could be any kind of Data Source (Database, Object, Web service), but for simplicity for trying out the designer, just use a database one which adds the typed data set into the Windows Forms project. Products is the table of data we will display in the grid, and Suppliers is the lookup table related through a foreign key column in the Products table that we want to display as a combo box of selectable values in the grid.
- Drag and drop Products from the Data Sources window onto the form. This will generate the grid, a data set instance, a table adapter to fill it, a BindingSource component hooked up to the data set and the Products table within it, a grid hooked up to the products binding source, and a binding navigator hooked up to the binding source.
- Click on the grid smart tag (little triangle on upper right border of control).
- Select Dock in Parent Container.
- Select Edit Columns.
- Select the SupplierID column in the list on the left.
- Select the ColumnType property and set it to DataGridViewComboBoxColumn.
- Select the DataSource property and navigate down through the data source tree through Other Data Sources > Project Data Sources > NorthwindDataSet > Suppliers table.
10. Select the DisplayMember property and select CompanyName.
11. Select the ValueMember property and select SupplierID.
12. Click OK to close the Edit Columns dialog.
13. Run the app and observe that you get the drop down list of suppliers. Selecting a supplier actually changes the SupplierID column value for that row in the products table to the appropriate foreign key value.
You can download a completed sample that was generated with these steps here.