1 out of 1 rated this helpful Rate this topic

Adding DataGrid Web Server Controls to a Web Forms Page

Visual Studio .NET 2003

You can add and configure a DataGrid Web server control in a few steps in order to display data on the page. In many cases, you will refine the grid to format the columns or add editing or sorting.

The following procedure describes the basic steps to create a working DataGrid control.

To add a DataGrid Web server control to a Web Forms page

  1. Add a data source to the Web Forms page. There are several methods for handling data in a Web application. To choose an appropriate method, see Introduction to Data Access with ADO.NET and Introduction to Data Access in Web Forms Pages.
  2. In Design view, drag a DataGrid control from the Web Forms tab of the Toolbox onto the page.
  3. Set the control's DataSource property. In the Properties window, the drop-down list for the DataSource property will display all the data sources, such as DataSet and DataView controls, defined on the page.

    By default, the DataGrid control will generate a bound column for each field in the data source. Each field in the data source is rendered in a separate column, 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.

  4. In code, call the control's DataBind method. This is typically done the first time the page runs (when Page.IsPostBack is false) in the page's Page_Load event using code as shown below. The DataBind method needs to be called whenever the data changes. On subsequent round trips of the page (when Page.IsPostBack is true), the DataBind method is typically called in the event handler, such as the paging event, PageIndexChanged, when the data you wish to display in the grid changes.
    ' Visual Basic
    Private Sub Page_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
       'Put user code to initialize the page here
       If Not Page.IsPostBack Then
       ' Put user code here to initialize the data source 
       ' (such as filling a dataset)
          DataGrid1.DataBind()
       End If
    End Sub
    
    // C#
    private void Page_Load(object sender, System.EventArgs e)
    {
       if (!Page.IsPostBack) 
       {
          // Put user code here to initialize the data source 
          // (such as filling a dataset)
          DataGrid1.DataBind();
       }
    }
    

See Also

DataGrid Web Server Control | Introduction to the DataGrid Web Server Control

Did you find this helpful?
(1500 characters remaining)