It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one. (Details are provided later in this paper.) Controlling Column Width, Height, and Alignment By default, the DataGrid control sizes rows and columns to fit the overall height and width that you have assigned to the grid. Within the overall grid width, it sizes columns according to the width of the column heading text. All data is displayed left-justified by default.
To control column characteristics, you should turn off auto column generation by setting the AutoGenerateColumns property to false. In fact, you should set this property to true only for short-term uses, such as quick proof-of-concept pages or demonstrations. For production applications, you should add columns explicitly. The individual columns can be bound columns or template columns.
To set the column width, you create a style element for that column and then set the element's Width property to standard units (say, pixels). The following example shows you what the HTML syntax looks like for an ItemStyle element with its Width property set.
<asp:BoundColumn DataField="title" SortExpression="title" HeaderText="Title"> <ItemStyle Width="100px"></ItemStyle> </asp:BoundColumn> Alternatively, you can do the same thing by setting the ItemStyle property directly in the element, as in the following example:
<asp:BoundColumn ItemStyle-Width="100px" DataField="title" SortExpression="title" HeaderText="Title"> </asp:BoundColumn> You can set alignment using the style element, setting it to "Right," "Left," and other values defined in the HorizontalAlign enumeration. (In Visual Studio, alignment is available for individual columns in the Format tab of the grid's Property builder.) The following is an example:
<asp:BoundColumn DataField="title" SortExpression="title" HeaderText="Title"> <ItemStyle Width="100px" HorizontalAlign="Right"></ItemStyle> </asp:BoundColumn> You can also set a column's height using the style element (or the ItemStyle-Height property). You will probably find this less flexible than setting the width, since setting the height for one column sets it for all of them.
You can set the width in code at run time as well. One place to do so is in an ItemCreated event handler. The following example sets the width of the first two columns to 100 and 50 pixels, respectively: