asp.net.ph

Skip Navigation Links

Adding DataGrid Controls to a Web Forms Page

Controls You Can Use on Web Forms   ASP.NET Data Controls   DataGrid Control


Essentially, to create a working DataGrid control, you need to add the control to the page and bind the control to a data source.

The below procedures show the minimum steps needed to display data in a DataGrid control.

To add a DataGrid control to a Web Forms page

This example shows a DataGrid control that is bound to a SqlDataSource control.

  1. Declare an <asp:DataGrid> element on the page. For syntax, see DataGrid Control Syntax.
  2. Specify the control’s DataSourceID property.
  3. Optionally set the grid’s base properties.

<asp:datagrid id="CustomersDataGrid" runat="server"
   datasourceid="customers"
   width=90% cellpadding=5
   font-size="9pt" />
Binding a DataGrid to a Data Source Control
Run Sample | View Source

The DataSource property of a DataGrid can also be set programmatically, just like any Web server control property. Below shows an example of binding a data source to a DataGrid in code.

<script language="C#" runat="server">
   protected void Page_Load ( object src, EventArgs e ) {
      string query = "SELECT ProductType, ProductCode, ... FROM Products";
      myGrid.DataSource = fetchReader ( query, "dbtutor" );
      myGrid.DataBind ( );
   }
</script>
Binding a DataGrid Control to a Data Source
Run Sample | View Source

NOTE: The DataGrid Web server control must have a value set either for its DataSourceID or DataSource property before it can render on the page.

The above examples apply several concepts and methods that are described elsewhere in this workshop. For particulars, see ADO.NET Primer, Introduction to Data Binding in Web Forms, Web Forms Server Controls Templates.

By default, the DataGrid control will generate a bound column for each field in the data source, in the order it occurs in the data source. Field names appear in the grid’s column headers, and values are rendered in text labels.

In case you need or want to customize the default format of the grid, you can choose which columns in the data source will render in the grid, and in what column type.

See Also

Introduction to the DataGrid Control   Adding Bound Columns to a DataGrid Control   Adding Button Columns to a DataGrid Control   Adding Hyperlink Columns to a DataGrid Control   Adding Template Columns to a DataGrid Control



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note