Export (0) Print
Expand All

DataGrid Class

A data bound list control that displays the items from data source in a table. The DataGrid control allows you to select, sort, and edit these items.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)

public class DataGrid extends BaseDataList implements INamingContainer
<asp:DataGrid />

Use the DataGrid control to display the fields of a data source as columns in a table. Each row in the DataGrid control represents a record in the data source. The DataGrid control supports selection, editing, deleting, paging, and sorting.

Different column types determine the behavior of the columns in the control. The following table lists the different column types that can be used.

Column Type

Description

BoundColumn

Displays a column bound to a field in a data source. It displays each item in the field as text. This is the default column type of the DataGrid control.

ButtonColumn

Displays a command button for each item in the column. This allows you to create a column of custom button controls, such as Add or Remove buttons.

EditCommandColumn

Displays a column that contains editing commands for each item in the column.

HyperLinkColumn

Displays the contents of each item in the column as a hyperlink. The contents of the column can be bound to a field in a data source or static text.

TemplateColumn

Displays each item in the column following a specified template. This allows you to provide custom controls in the column.

By default, the AutoGenerateColumns property is set to true, which creates a BoundColumn object for each field in the data source. Each field is then rendered as a column in the DataGrid control in the order that each field appears in the data source.

You can also manually control which columns appear in the DataGrid control by setting the AutoGenerateColumns property to false and then listing the columns that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. This allows you to programmatically control the columns in the DataGrid control.

NoteNote:

The order that the columns are displayed in the DataGrid control is controlled by the order that the columns appear in the Columns collection. Although you can programmatically change the order of the columns by manipulating the Columns collection, it is easier to list the columns in the desired display order.

Explicitly declared columns can be displayed in conjunction with automatically generated columns. When using both, explicitly declared columns will be rendered first, followed by the automatically generated columns.

NoteNote:

Automatically generated columns are not added to the Columns collection.

The appearance of the DataGrid control may be customized by setting the style properties for the different parts of the control. The following table lists the different style properties.

Style Property

Description

AlternatingItemStyle

Specifies the style for alternating items in the DataGrid control.

EditItemStyle

Specifies the style for the item being edited in the DataGrid control.

FooterStyle

Specifies the style for the footer section in the DataGrid control.

HeaderStyle

Specifies the style for the header section in the DataGrid control.

ItemStyle

Specifies the style for the items in the DataGrid control.

PagerStyle

Specifies the style for the page selection section of the DataGrid control.

SelectedItemStyle

Specifies the style for the selected item in the DataGrid control.

You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

Property

Description

ShowFooter

Shows or hides the footer section of the DataGrid control.

ShowHeader

Shows or hides the header section of the DataGrid control.

You can control the appearance of the DataGrid control by programmatically adding attributes to the <td> and <tr> tags rendered by the control on the browser. Attributes can be programmatically added by providing code in the event handler for the OnItemCreated or OnItemDataBound event.

To add an attribute to the <td> tag, first get the TableCell object that represents the cell in the DataGrid control you want to add the attribute to. The Control.Controls collection for the Item property of the DataGridItemEventArgs object passed into the event handler can be used to get the desired TableCell object. You can then use the AttributeCollection.Add method of the Attributes collection for the TableCell object to add attributes to the <td> tag.

To add an attribute to the <tr> tag, first get the DataGridItem object that represents the row in the DataGrid control you want to add the attribute to. The Item property of the DataGridItemEventArgs object passed into the event handler can be used to get the desired DataGridItem object. You can then use the AttributeCollection.Add method of the Attributes collection for the DataGridItem object to add attributes to the <tr> tag.

Caution noteCaution:

This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. ASP.NET provides an input request validation feature to block script and HTML in user input. Validation server controls are also provided to assess user input. For more information, see Validation Server Control Syntax.

Accessibility

The markup rendered by default for this control might not conform to accessibility standards such as the Web Content Accessibility Guidelines 1.0 (WCAG) priority 1 guidelines. For details about accessibility support for this control, see ASP.NET Controls and Accessibility.

The following code example demonstrates how to use the DataGrid control to display the items in the data source.

No code example is currently available or this language may not be supported.

The following code example demonstrates how to use the DataGrid control for a simple shopping cart.

No code example is currently available or this language may not be supported.

The following code example demonstrates how to dynamically add attributes to the <td> and <tr> tags generated by the DataGrid control.

<%@ Page Language="JScript" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">

   function CreateDataSource() : ICollection
   {
      var dt : DataTable = new DataTable();
      var dr : DataRow;

      dt.Columns.Add(new DataColumn("IntegerValue", System.Int32));
      dt.Columns.Add(new DataColumn("StringValue", System.String));
      dt.Columns.Add(new DataColumn("CurrencyValue", System.Double));

      for (var i : int = 0; i < 5; i++) 
      {
         dr = dt.NewRow();

         dr[0] = i;
         dr[1] = "Item " + i.ToString();
         dr[2] = 1.23 * (i+1);

         dt.Rows.Add(dr);
      }

      var dv : DataView = new DataView(dt);
      return dv;
   }

   function Page_Load(sender, e: EventArgs) 
   {

      if (!IsPostBack) 
      {
         // Load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }

   }

   function Item_Bound(sender, e : DataGridItemEventArgs) 
   {

      var itemType : ListItemType  = ListItemType(e.Item.ItemType);

      if ((itemType != ListItemType.Header) &&
          (itemType != ListItemType.Footer) &&
          (itemType != ListItemType.Separator))
      {

         // Get the IntegerValue cell from the grid's column collection.
         var intCell : TableCell = TableCell(e.Item.Controls[0]);

         // Add attributes to the cell.
         intCell.Attributes.Add("id", "intCell" + e.Item.ItemIndex.ToString());
         intCell.Attributes.Add("OnClick", 
                                "Update_intCell" + 
                                e.Item.ItemIndex.ToString() + 
                                "()");

         // Add attributes to the row.
         e.Item.Attributes.Add("id", "row" + e.Item.ItemIndex.ToString());
         e.Item.Attributes.Add("OnDblClick", 
                                "Update_row" + 
                                e.Item.ItemIndex.ToString() + 
                                "()");

      }

   }

</script>

<script type="text/vbscript">

   sub Update_intCell0 
      Alert "You Selected Cell 0."
   end sub

   sub Update_intCell1 
      Alert "You Selected Cell 1."
   end sub

   sub Update_intCell2 
      Alert "You Selected Cell 2."
   end sub

   sub Update_intCell3 
      Alert "You Selected Cell 3."
   end sub

   sub Update_intCell4 
      Alert "You Selected Cell 4."
   end sub

   sub UpDate_row0 
      Alert "You selected the row 0."
   end sub

   sub UpDate_row1 
      Alert "You selected the row 1."
   end sub

   sub UpDate_row2 
      Alert "You selected the row 2."
   end sub

   sub UpDate_row3 
      Alert "You selected the row 3."
   end sub

   sub UpDate_row4 
      Alert "You selected the row 4."
   end sub   

</script>

<head runat="server">
    <title>

            Adding Attributes to the &lt;td&gt; and &lt;tr&gt; </title>
</head>
<body>

   <form id="form1" runat="server">

      <h3>

            Adding Attributes to the &lt;td&gt; and &lt;tr&gt; <br />
            Tags of a DataGrid Control

      </h3>

      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           ShowFooter="true"
           OnItemDataBound="Item_Bound"
           AutoGenerateColumns="false">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <FooterStyle BackColor="#00aaaa">
         </FooterStyle>

         <Columns>

            <asp:BoundColumn HeaderText="Number" 
                 DataField="IntegerValue">

               <ItemStyle BackColor="yellow">
               </ItemStyle>

            </asp:BoundColumn>

            <asp:BoundColumn
                 HeaderText="Item" 
                 DataField="StringValue"/>

            <asp:BoundColumn 
                 HeaderText="Price" 
                 DataField="CurrencyValue" 
                 DataFormatString="{0:c}">

               <ItemStyle HorizontalAlign="right">
               </ItemStyle>

            </asp:BoundColumn>

         </Columns>

      </asp:DataGrid>

      <br /><br />

      Click on one of the cells in the <b>Number</b> column to select the cell.

      <br /><br />

      Double click on a row to select a row.   

   </form>

</body>
</html>
No code example is currently available or this language may not be supported.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft