Binding data to a DataGrid , DataList , or Repeater control is easiest of all. All you have to do is have an object that implements IEnumerable , assign this object to the DataSource property of the prospective control, and invoke DataBind on that control. The ease with which you can get data into these controls in no way mitigates their utility. You can perform mundane tasks , like simply binding a DataView object, or create elaborate, complex interfaces with a bit of clever invention. (Read the Using a DataList Control to Repeat Composite Controls section later in this chapter for more information.)
Refer to Listing 16.4 for a quick example of getting a DataView object into a DataGrid control. Listing 16.7 demonstrates how we can use a DataGrid control and specific bound columns as an alternate way to refine the view of data. Listing 16.7 uses the lazy Contacts instance from Listing 16.6 but specifies bound columns instead of auto-generating columns. In the example I bound only the contact name and phone number from the Contacts data view. Figure 16.8 shows the results.
Listing 16.7 Binding Specific Data to a DataGrid Control
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Binds the Contacts data view to the DataList control DataGrid1.DataSource = Contacts DataGrid1.DataBind() End Sub
Figure 16.8. The result of binding specific columns to a DataGrid control instead of allowing the grid to autogenerate the columns.
The code in Listing 16.7 relies on the previously mentioned lazy instance of the Contacts data view from the Contacts property, the GetContacts method, and the Database class. It is important to understand that the code in Listing 16.7 demonstrates how we would bind any data source to a DataGrid control.
Here are the steps for limiting the bound columns for the DataGrid control, as shown in Figure 16.8.
If you add the code from Listing 16.7 to the Page_Load event in Listing 16.6, you can run the application and see the results as shown in Figure 16.8.
Using the DataGrid control in the manner prescribed is pretty basic. In the next section we'll look at how the DataGrid control supports paging and sorting. The section after that will demonstrate how we can use a variation of the technique described in this section to repeat complex user controls, resulting in professional and elaborate-looking user interfaces.