DataGrid 类

数据绑定列表控件,它在表中显示来自数据源的项。DataGrid 控件允许您选择和编辑这些项以及对它们进行排序。

**命名空间:**System.Web.UI.WebControls
**程序集:**System.Web(在 system.web.dll 中)

语法

声明
Public Class DataGrid
    Inherits BaseDataList
    Implements INamingContainer
用法
Dim instance As DataGrid
public class DataGrid : BaseDataList, INamingContainer
public ref class DataGrid : public BaseDataList, INamingContainer
public class DataGrid extends BaseDataList implements INamingContainer
public class DataGrid extends BaseDataList implements INamingContainer

备注

使用 DataGrid 控件可以将数据源的字段作为表中的列显示。DataGrid 控件中的每一行表示数据源中的一个记录。DataGrid 控件支持选择、编辑、删除、分页和排序。

不同的列类型决定控件中各列的行为。下表列出了可以使用的不同列类型。

列类型

说明

BoundColumn

显示绑定到数据源中的字段的列。它以文本形式显示字段中的每个项。这是 DataGrid 控件的默认列类型。

ButtonColumn

为列中每个项显示一个命令按钮。这使您可以创建一列自定义按钮控件,如 Add 按钮或 Remove 按钮。

EditCommandColumn

显示一列,该列包含列中各个项的编辑命令。

HyperLinkColumn

将列中各项的内容显示为超链接。列的内容可以绑定到数据源或静态文本中的字段。

TemplateColumn

按照指定的模板显示列中的各项。这使您可以在列中提供自定义控件。

默认情况下,AutoGenerateColumns 属性被设置为 true,为数据源中的每一个字段创建一个 BoundColumn 对象。每个字段然后作为 DataGrid 控件中的列呈现,其顺序同于每一字段在数据源中出现的顺序。

您还可以手动控制在 DataGrid 控件中显示哪些列,方法是首先将 AutoGenerateColumns 属性设置为 false,然后列出您要包括在开始和结束 <Columns> 标记之间的列。指定的列将以所列出的顺序添加到 Columns 集合中。这允许您以编程的方式控制 DataGrid 控件中的列。

提示

列在 DataGrid 控件中显示的顺序由列在 Columns 集合中出现的顺序控制。尽管您可以通过操作 Columns 集合以编程方式更改列的顺序,但以所需的显示顺序列出列更为容易。

显式声明的列可与自动生成的列一起显示。当同时使用这二者时,首先呈现的是显式声明的列,其后是自动生成的列。

提示

自动生成的列不会添加到 Columns 集合中。

可以通过为 DataGrid 控件的不同部分设置样式属性来自定义该控件的外观。下表列出了不同的样式属性。

样式属性

说明

AlternatingItemStyle

指定 DataGrid 控件中交替项的样式。

EditItemStyle

指定 DataGrid 控件中正在编辑的项的样式。

FooterStyle

指定 DataGrid 控件中页脚部分的样式。

HeaderStyle

指定 DataGrid 控件中页眉部分的样式。

ItemStyle

指定 DataGrid 控件中项的样式。

PagerStyle

指定 DataGrid 控件中页选择部分的样式。

SelectedItemStyle

指定 DataGrid 控件中选定项的样式。

也可以显示或隐藏控件的不同部分。下表列出控制显示或隐藏哪些部分的属性。

属性

说明

ShowFooter

显示或隐藏 DataGrid 控件的页脚部分。

ShowHeader

显示或隐藏 DataGrid 控件的页眉部分。

您可以控制 DataGrid 控件的外观,方法是以编程的方式将属性添加到浏览器上该控件呈现的 <td><tr> 标记中。可以通过编程的方式添加属性,方法是为 OnItemCreatedOnItemDataBound 事件提供事件处理程序中的代码。

若要将属性添加到 <td> 标记,请首先获取 TableCell 对象,该对象表示您要将属性添加到其中的 DataGrid 控件中的单元格。可以使用传递到事件处理程序的 DataGridItemEventArgs 对象的 Item 属性的 Control.Controls 集合来获取所需的 TableCell 对象。然后可以使用 TableCell 对象的 Attributes 集合的 AttributeCollection.Add 方法来将属性添加到 <td> 标记。

若要将属性添加到 <tr> 标记,请首先获取 DataGridItem 对象,该对象表示您要将属性添加到其中的 DataGrid 控件中的行。可以使用传递到事件处理程序的 DataGridItemEventArgs 对象的 Item 属性获取所需的 DataGridItem 对象。然后可以使用 DataGridItem 对象的 Attributes 集合的 AttributeCollection.Add 方法来将属性添加到 <tr> 标记。

警告

此控件可用来显示用户输入,而该输入可能包含恶意的客户端脚本。在应用程序中显示从客户端发送来的任何信息之前,请检查它们是否包含可执行脚本、SQL 语句或其他代码。ASP.NET 提供输入请求验证功能以阻止用户输入中的脚本和 HTML。还提供验证服务器控件以判断用户输入。有关更多信息,请参见 验证服务器控件语法

辅助功能

默认情况下为此控件呈现的标记可能不符合 Web 内容辅助功能准则 1.0 (WCAG) 中优先级为 1 的准则等辅助功能标准。有关此控件的辅助功能支持的详细信息,请参见 ASP.NET 控件和辅助功能

示例

下面的代码示例演示如何使用 DataGrid 控件显示数据源中的项。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script language="VB" runat="server">
     Function CreateDataSource() As ICollection
        Dim dt As New DataTable()
        Dim dr As DataRow
        
        dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
        
        Dim i As Integer
        For i = 0 To 8
            dr = dt.NewRow()
            
            dr(0) = i
            dr(1) = "Item " + i.ToString()
            dr(2) = 1.23 *(i + 1)
            
            dt.Rows.Add(dr)
        Next i
        
        Dim dv As New DataView(dt)
        Return dv
    End Function 'CreateDataSource


    Sub Page_Load(sender As Object, e As EventArgs)
        
        If Not IsPostBack Then
            ' Load this data only once.
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub 'Page_Load
 
  </script>
 
<body>
 
   <form runat=server>
 
      <h3>DataGrid Example</h3>
 
      <b>Product List</b>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="true"
           runat="server">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle> 
 
      </asp:DataGrid>
 
   </form>
 
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script language="C#" runat="server">
 
      ICollection CreateDataSource() 
      {
         DataTable dt = new DataTable();
         DataRow dr;
 
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         return dv;
      }
 
      void Page_Load(Object sender, EventArgs e) 
      {
 
         if (!IsPostBack) 
         {
            // Load this data only once.
            ItemsGrid.DataSource= CreateDataSource();
            ItemsGrid.DataBind();
         }
      }
 
   </script>
 
<body>
 
   <form runat=server>
 
      <h3>DataGrid Example</h3>
 
      <b>Product List</b>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="true"
           runat="server">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle> 
 
      </asp:DataGrid>
 
   </form>
 
</body>
</html>

下面的代码示例演示如何将 DataGrid 控件用于简单购物车。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script language="VB" runat="server">
 
      Dim Cart As DataTable
      Dim CartView As DataView
      
        Function CreateDataSource() As ICollection
            Dim dt As New DataTable()
            Dim dr As DataRow
            
            dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
            dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
            dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
            
            Dim i As Integer
            For i = 0 To 8
                dr = dt.NewRow()
                
                dr(0) = i
                dr(1) = "Item " + i.ToString()
                dr(2) = 1.23 *(i + 1)
                
                dt.Rows.Add(dr)
            Next i
            
            Dim dv As New DataView(dt)
            Return dv
        End Function 'CreateDataSource


        Sub Page_Load(sender As Object, e As EventArgs)
            
            If Session("DG4_ShoppingCart") Is Nothing Then
                Cart = New DataTable()
                Cart.Columns.Add(New DataColumn("Item", GetType(String)))
                Cart.Columns.Add(New DataColumn("Price", GetType(String)))
                Session("DG4_ShoppingCart") = Cart
            
            Else
                Cart = CType(Session("DG4_ShoppingCart"), DataTable)
            End If
            
            CartView = New DataView(Cart)
            ShoppingCart.DataSource = CartView
            ShoppingCart.DataBind()
            
            If Not IsPostBack Then
                ' Load this data only once.
                ItemsGrid.DataSource = CreateDataSource()
                ItemsGrid.DataBind()
            End If
        End Sub 'Page_Load


        Sub Grid_CartCommand(sender As Object, e As DataGridCommandEventArgs)
            
            Dim dr As DataRow = Cart.NewRow()
            
            ' e.Item is the table row where the command is raised.
            ' For bound columns, the value is stored in the Text property of the TableCell.
            Dim itemCell As TableCell = e.Item.Cells(2)
            Dim priceCell As TableCell = e.Item.Cells(3)
            Dim item As String = itemCell.Text
            Dim price As String = priceCell.Text
            
            If CType(e.CommandSource, Button).CommandName = "AddToCart" Then
                dr(0) = item
                dr(1) = price
                Cart.Rows.Add(dr)
            
            Else 

                'Remove from Cart.
                CartView.RowFilter = "Item" + ChrW(61) + "'" + item + "'"
                If CartView.Count > 0 Then
                    CartView.Delete(0)
                End If
                CartView.RowFilter = ""
            End If
            
            ShoppingCart.DataBind()
        End Sub 'Grid_CartCommand 
   </script>
 
<body>
 
   <form runat=server>
 
   <h3>DataGrid Example</h3>
 
   <table cellpadding="5">
      <tr valign="top">
         <td>
 
            <b>Product List</b>
 
            <asp:DataGrid id="ItemsGrid"
                 BorderColor="black"
                 BorderWidth="1"
                 CellPadding="3"
                 AutoGenerateColumns="false"
                 OnItemCommand="Grid_CartCommand"
                 runat="server">

               <HeaderStyle BackColor="#00aaaa">
               </HeaderStyle>
 
               <Columns>
 
                  <asp:ButtonColumn 
                       HeaderText="Add to cart" 
                       ButtonType="PushButton" 
                       Text="Add" 
                       CommandName="AddToCart" />
 
                  <asp:ButtonColumn 
                       HeaderText="Remove from cart" 
                       ButtonType="PushButton" 
                       Text="Remove" 
                       CommandName="RemoveFromCart" />
 
                  <asp:BoundColumn 
                       HeaderText="Item" 
                       DataField="StringValue"/>

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

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

                  </asp:BoundColumn>   
 
               </Columns>
 
            </asp:DataGrid>
 
         </td>
         <td>
 
            <b>Shopping Cart</b>
 
            <asp:DataGrid id="ShoppingCart" 
                 runat="server"
                 BorderColor="black"
                 BorderWidth="1"
                 GridLines="Both"
                 ShowFooter="false"
                 CellPadding="3"
                 CellSpacing="0">

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

            </asp:DataGrid> 
 
         </td>
      </tr>
 
   </table>
 
   </form>
 
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script language="C#" runat="server">
 
      DataTable Cart;
      DataView CartView;
 
      ICollection CreateDataSource() 
      {
         DataTable dt = new DataTable();
         DataRow dr;
 
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         return dv;
      }
 
      void Page_Load(Object sender, EventArgs e) 
      {
     
         if (Session["DG4_ShoppingCart"] == null) 
         {
            Cart = new DataTable();
            Cart.Columns.Add(new DataColumn("Item", typeof(string)));
            Cart.Columns.Add(new DataColumn("Price", typeof(string)));
            Session["DG4_ShoppingCart"] = Cart;
         }

         else 
         {
            Cart = (DataTable)Session["DG4_ShoppingCart"];
         }    

         CartView = new DataView(Cart);
         ShoppingCart.DataSource = CartView;
         ShoppingCart.DataBind();
 
         if (!IsPostBack) 
         {
            // Load this data only once.
            ItemsGrid.DataSource= CreateDataSource();
            ItemsGrid.DataBind();
         }
      }
 
      void Grid_CartCommand(Object sender, DataGridCommandEventArgs e) 
      {
     
         DataRow dr = Cart.NewRow();
         
         // e.Item is the table row where the command is raised.
         // For bound columns, the value is stored in the Text property of the TableCell.
         TableCell itemCell = e.Item.Cells[2];
         TableCell priceCell = e.Item.Cells[3];
         string item = itemCell.Text;
         string price = priceCell.Text;
          
         if (((Button)e.CommandSource).CommandName == "AddToCart") 
         {
            dr[0] = item;
            dr[1] = price;
            Cart.Rows.Add(dr);
         }

         else 
         {  

            // Remove from Cart.
         
            CartView.RowFilter = "Item='" + item + "'";
            if (CartView.Count > 0) 
            {     
               CartView.Delete(0);
            }
            CartView.RowFilter = "";
         }

         ShoppingCart.DataBind();
 
      }
 
 
   </script>
 
<body>
 
   <form runat=server>
 
   <h3>DataGrid Example</h3>
 
   <table cellpadding="5">
      <tr valign="top">
         <td>
 
            <b>Product List</b>
 
            <asp:DataGrid id="ItemsGrid"
                 BorderColor="black"
                 BorderWidth="1"
                 CellPadding="3"
                 AutoGenerateColumns="false"
                 OnItemCommand="Grid_CartCommand"
                 runat="server">

               <HeaderStyle BackColor="#00aaaa">
               </HeaderStyle>
 
               <Columns>
 
                  <asp:ButtonColumn 
                       HeaderText="Add to cart" 
                       ButtonType="PushButton" 
                       Text="Add" 
                       CommandName="AddToCart" />
 
                  <asp:ButtonColumn 
                       HeaderText="Remove from cart" 
                       ButtonType="PushButton" 
                       Text="Remove" 
                       CommandName="RemoveFromCart" />
 
                  <asp:BoundColumn 
                       HeaderText="Item" 
                       DataField="StringValue"/>

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

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

                  </asp:BoundColumn>   
 
               </Columns>
 
            </asp:DataGrid>
 
         </td>
         <td>
 
            <b>Shopping Cart</b>
 
            <asp:DataGrid id="ShoppingCart" 
                 runat="server"
                 BorderColor="black"
                 BorderWidth="1"
                 GridLines="Both"
                 ShowFooter="false"
                 CellPadding="3"
                 CellSpacing="0">

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

            </asp:DataGrid> 
 
         </td>
      </tr>
 
   </table>
 
   </form>
 
</body>
</html>

下面的代码示例演示如何动态将属性添加到由 DataGrid 控件生成的 <td><tr> 标记。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
<script runat="server">
 
   Function CreateDataSource() As ICollection 
   
      Dim dt As DataTable = New DataTable()
      Dim dr As DataRow
      Dim i As Integer
      Dim dv As DataView
 
      dt.Columns.Add(New DataColumn("IntegerValue", GetType(Integer)))
      dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
      dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
 
      For i = 0 to 4 

         dr = dt.NewRow()
 
         dr(0) = i
         dr(1) = "Item " + i.ToString()
         dr(2) = 1.23 * (i+1)
 
         dt.Rows.Add(dr)
      
      Next i
 
      dv = New DataView(dt)
      CreateDataSource = dv
   
   End Function
 
   Sub Page_Load(sender As Object, e As EventArgs) 
 
      If Not IsPostBack 
  
         ' Load this data only once.
         ItemsGrid.DataSource = CreateDataSource()
         ItemsGrid.DataBind()
      
      End If 
 
   End Sub
 
   Sub Item_Bound(sender As Object, e As DataGridItemEventArgs) 

      Dim itemType As ListItemType 
      Dim intCell As TableCell

      itemType = CType(e.Item.ItemType, ListItemType)

      If (itemType <> ListItemType.Header) And _
         (itemType <> ListItemType.Footer) And _
         (itemType <> ListItemType.Separator) Then

         ' Get the IntegerValue cell from the grid's column collection.
         intCell = CType(e.Item.Controls(0), TableCell)

         ' 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() + _
                                "()")

      End If
 
   End Sub
 
</script>

<script language="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>
 
<body>
 
   <form 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>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
<script runat="server">
 
   ICollection CreateDataSource() 
   {
      DataTable dt = new DataTable();
      DataRow dr;
 
      dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
      dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
      dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
      for (int i = 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);
      }
 
      DataView dv = new DataView(dt);
      return dv;
   }
 
   void Page_Load(Object sender, EventArgs e) 
   {
 
      if (!IsPostBack) 
      {
         // Load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }
 
   }
 
   void Item_Bound(Object sender, DataGridItemEventArgs e) 
   {

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

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

         // Get the IntegerValue cell from the grid's column collection.
         TableCell intCell = (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 language="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>
 
<body>
 
   <form 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>
<%@ Page Language="JScript" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
<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 language="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>
 
<body>
 
   <form 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>
<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">
 
       Function CreateDataSource() As ICollection 
      
         ' Create sample data for the DataGrid control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow
 
         ' Define the columns of the table.
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(string)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(double)))
 
         ' Populate the table with sample values.
         Dim i As Integer

         For i = 0 to 8 
        
            dr = dt.NewRow()
 
            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * (i + 1)
 
            dt.Rows.Add(dr)

         Next i
 
         Dim dv As DataView = New DataView(dt)
         Return dv

      End Function
 
      Sub Page_Load(sender As Object, e As EventArgs) 
 
         ' Load sample data only once when the page is first loaded.
         If Not IsPostBack Then 
  
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()

         End If

      End Sub

      Sub Button_Click(sender As Object, e As EventArgs) 

         ' Count the number of selected items in the DataGrid control.
         Dim count As Integer = 0

         ' Display the selected items.
         Message.Text = "You Selected: <br>"

         ' Iterate through each item (row) in the DataGrid control 
         ' and determine whether it is selected.
         Dim item As DataGridItem
 
         For Each item In ItemsGrid.Items

            DetermineSelection(item, count)        

         Next

         ' If no items are selected, display the appropriate message.
         If count = 0 Then

            Message.Text = "No items selected"

         End If

      End Sub

      Sub DetermineSelection(item As DataGridItem, ByRef count As Integer)

         ' Retrieve the SelectCheckBox CheckBox control from the specified  
         ' item (row) in the DataGrid control.
         Dim selection As CheckBox = CType(item.FindControl("SelectCheckBox"), CheckBox)

         ' If the item is selected, display the appropriate message and 
         ' increment the count of selected items.
         If Not selection Is Nothing Then

           If selection.Checked Then
           
              Message.Text &= "- " & item.Cells(1).Text & "<br>"
              count = count + 1
           
           End If

         End If    

      End Sub

   </script>
 
<body>
 
   <form runat=server>
 
      <h3>DataGrid Example</h3>
 
      <b>Product List</b>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="False"
           runat="server">

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

         <Columns>

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

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

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

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>

            </asp:BoundColumn>

            <asp:TemplateColumn HeaderText="Select Item">

               <ItemTemplate>

                  <asp:CheckBox id="SelectCheckBox"
                       Text="Add to Cart"
                       Checked="False"
                       runat="server"/>

               </ItemTemplate>

            </asp:TemplateColumn>
 
         </Columns> 
 
      </asp:DataGrid>

      <br><br>

      <asp:Button id="SubmitButton"
           Text="Submit"
           OnClick = "Button_Click"
           runat="server"/>

      <br><br>

      <asp:Label id="Message"
           runat="server"/>
 
   </form>
 
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">
 
      ICollection CreateDataSource() 
      {
      
         // Create sample data for the DataGrid control.
         DataTable dt = new DataTable();
         DataRow dr;
 
         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         // Populate the table with sample values.
         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         return dv;
      }
 
      void Page_Load(Object sender, EventArgs e) 
      {
 
         // Load sample data only once when the page is first loaded.
         if (!IsPostBack) 
         {
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
         }

      }

      void Button_Click(Object sender, EventArgs e) 
      {

         // Count the number of selected items in the DataGrid control.
         int count = 0;

         // Display the selected times.
         Message.Text = "You Selected: <br>";

         // Iterate through each item (row) in the DataGrid control and 
         // determine whether it is selected.
         foreach (DataGridItem item in ItemsGrid.Items)
         {

            DetermineSelection(item, ref count);        

         }

         // If no items are selected, display the appropriate message.
         if (count == 0)
         {

            Message.Text = "No items selected";

         }

      }

      void DetermineSelection(DataGridItem item, ref int count)
      {

         // Retrieve the SelectCheckBox CheckBox control from the specified 
         // item (row) in the DataGrid control.
         CheckBox selection = (CheckBox)item.FindControl("SelectCheckBox");

         // If the item is selected, display the appropriate message and 
         // increment the count of selected items.
         if (selection != null)
         {

           if (selection.Checked)
           {
              Message.Text += "- " + item.Cells[1].Text + "<br>";
              count++;
           }

         }    

      }

   </script>
 
<body>
 
   <form runat=server>
 
      <h3>DataGrid Example</h3>
 
      <b>Product List</b>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="False"
           runat="server">

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

         <Columns>

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

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

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

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>

            </asp:BoundColumn>

            <asp:TemplateColumn HeaderText="Select Item">

               <ItemTemplate>

                  <asp:CheckBox id="SelectCheckBox"
                       Text="Add to Cart"
                       Checked="False"
                       runat="server"/>

               </ItemTemplate>

            </asp:TemplateColumn>
 
         </Columns> 
 
      </asp:DataGrid>

      <br><br>

      <asp:Button id="SubmitButton"
           Text="Submit"
           OnClick = "Button_Click"
           runat="server"/>

      <br><br>

      <asp:Label id="Message"
           runat="server"/>
 
   </form>
 
</body>
</html>

继承层次结构

System.Object
   System.Web.UI.Control
     System.Web.UI.WebControls.WebControl
       System.Web.UI.WebControls.BaseDataList
        System.Web.UI.WebControls.DataGrid

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

DataGrid 成员
System.Web.UI.WebControls 命名空间
BaseDataList 类
DataList
Repeater
BoundColumn 类
ButtonColumn 类
EditCommandColumn
HyperLinkColumn
TemplateColumn