DataGrid ControlYou are likely to use the DataGrid control to display fields of a DataSource when you want to display them as columns in a table. Each row in the DataGrid control, as with Repeater and DataList controls, represents a record in the DataSource . The DataGrid control is richer than the Repeater and the DataList . It supports selections, editing, deleting, paging, and sorting. Five different column types are available for the DataGrid control. They can be seen in Table 10.3. Table 10.3. The DataGrid Column Types
The DataGrid control automatically generates columns based on the data to which it is bound. This means that if your DataSource has five columns, the DataGrid control appears with five columns in your page. A property named AutoGenerateColumns is a part of the DataGrid control. This property, if it is true (which is the default), auto-generates columns. If it is false, the columns are not auto-generated, and you must then specify BoundColumn objects in the ItemTemplate for data columns to appear. The following code is a DataGrid that automatically binds data and generates columns: <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" AutoGenerateColumns="true" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> </asp:DataGrid> The following code shows a DataGrid control that does not automatically bind the columns to display columns. Instead, it sets the AutoGenerateColumns property to False, and then determines which columns are to be displayed and bound. <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" AutoGenerateColumns="false" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:ButtonColumn HeaderText="Add to cart" ButtonType="PushButton" Text="Add" /> <asp:BoundColumn HeaderText="Item" DataField="StringValue"> <ItemStyle HorizontalAlign="right"> </ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> Just like the Repeater and the DataList controls, the DataGrid has templates with which it determines how to render the data. These can be seen in Table 10.4. Table 10.4. The DataGrid Templates
You can also control the appearance of the DataGrid control by programmatically adding attributes to the <TD> <TR> tags rendered by the control on the browser. Attributes can be added programmatically if you provide code in the event handler for the OnItemCreated or OnItemDataBound events. To add an attribute to the <TD> tag, first get the table cell object that represents the cell and the DataGrid control to which you want to add the attribute. The control's collection for the Item property of the DataGridItemEvent object is passed into the event handler, and can be used to get the desired table cell object. Then, you can use the AttributeCollection.Add() method of the attribute's collection for the table cell object to add attributes to the <TD> tag. |