Adding boundfields to a GridView control
To establish control over displaying columns in a GridView control, we have to set the AutoGenerateColumns property to ‘false’ and define a BoundField object for each column to be displayed in the GridView.
Using BoundFields, we can customize the header text by setting the HeaderText property. To format the data displayed in the GridView column we use DataFormatString property of BoundField.
When we use a BoundField for a column, the value of a data item is displayed as text. We need to use one
only, for each column. The tag has three important properties.
| Property |
Description |
| DataField |
Specifies the name of the field that the boundfield displays |
| HeaderText |
Displays text in the column header |
| DataFormatString |
Specifies the format string to format a data item |
Other properties we can use with column are:
| Property |
Description |
| FooterStyle |
Enables footer column formatting |
| FooterText |
Enables text display in the column footer |
| HeaderStyle |
Enables header column formatting |
| HeaderText |
Enables text display in the column header |
| ItemStyle |
Enables to format a data item |
Steps to create a column are:
The first step is to declare a GridView control and set the AutoGenerateColumns property to ‘false’.
Next, create a element within the element. Define a element for each column we want to display as text. Specify the name of the field we want to display in the DataField property.
<asp:GridView ID=”GridView1" DataSourceId=”MyDataSource” DataKeyNames=”AccountCode” ShowFooter=”true” AutoGenerateColumns=”false”
AutoGenerateEditButton=”true” AutoGenerateDeleteButton=”true”
runat=”server”>
<Columns>
<asp:BoundField DataField=”AccountCode” HeaderText=”Account Code”>
<ItemStyle Font-Size=”Large” />
</asp:BoundField>
<asp:BoundField DataField=”AccountName” HeaderText=”Account Name”
FooterText=”Enter Footer Text”>
<FooterStyle CssClass=”FooterStyle” />
</asp:BoundField >
<asp:BoundField DataField=”AccountDescription” HeaderText=”Description” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”MyDataSource”
ConnectionString=”<%$Connectionstrings:ERPConnectionString%>”
SelectCommand=”SELECT AccountsTable.AccountCode,AccountsTable.AccountName,
AccountsTable.AccountDescription FROM AccountsTable”
UpdateCommand=”Update AccountsTable SET AccountName=@AccountName,
AccountDescription=@AccountDescription Where AccountCode=@AccountCode”
DeleteCommand=”Delete AccountsTable Where AccountCode=@AccountCode” runat=”server”/>
