asp.net.ph

Skip Navigation Links

Adding GridView Controls to a Web Forms Page

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


Essentially, to create a working GridView 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 GridView control.

To add a GridView control to a Web Forms page

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

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

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

The DataSource property of a GridView can also be set programmatically, just like any Web server control property. Below shows an example of binding a data source to a GridView 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 GridView Control to a Data Source
Run Sample | View Source

NOTE: The GridView 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 GridView 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 fields in the data source will render in the grid, and in what field type.

See Also

Introduction to the GridView Control   Adding Bound Fields to a GridView 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