DataGrid 类 | DataGrid 成员 | System.Web.UI.WebControls 命名空间 | DataGridColumn | BoundColumn | ButtonColumn | EditCommandColumn | HyperLinkColumn | TemplateColumn | DataGrid 成员(Visual J# 语法) | C++ 托管扩展编程

平台: Windows 2000, Windows XP Professional, Windows Server 2003 系列

  • JScript
  • Visual Basic

    获取表示 DataGrid 控件的各列的对象的集合。

    [Visual Basic]
    Public Overridable ReadOnly Property Columns As _
       DataGridColumnCollection
    public virtual DataGridColumnCollection Columns {get;}

    [C++]
    public: __property virtual DataGridColumnCollection* get_Columns();

    [JScript]
    public function get Columns() : DataGridColumnCollection;

    一个 DataGridColumnCollection 对象,该对象包含表示 DataGrid 控件中各列的对象的集合。

    使用此属性以编程的方式控制 DataGrid 控件中各列的集合。 Columns 集合包含 DataGrid 控件中呈现的显式声明的列。

    注意 显式声明的列可与自动生成的列一起使用。当同时使用这二者时,首先呈现的是显式声明的列,其后是自动生成的列。自动生成的列不会添加到 Columns 集合中。

    列在 DataGrid 控件中显示的顺序由列在 Columns 集合中出现的顺序控制。

    下表显示从 DataGridColumn 类导出并且可在 Columns 集合中使用的不同列类。

    注意 尽管您可以编程的方式将列添加到 Columns 集合,但静态地列出相应列然后使用 Visible 属性显示或隐藏列更容易一些。

    示例

    [Visual Basic, C#, JScript] 下面的示例展示如何使用 Columns 集合动态向 DataGrid 控件添加列。

    [Visual Basic] 
    <%@ Page Language="VB" AutoEventWireup="True" %>
    <%@ Import Namespace="System.Data" %>
       <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
                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 Page_Init(sender As Object, e As EventArgs)
            ' Create a dynamic column to add to Columns collection.
            Dim NumberColumn As New BoundColumn()
            NumberColumn.HeaderText = "Item Number"
            NumberColumn.DataField = "IntegerValue"
            ' Add column to Columns collection.
            ItemsGrid.Columns.AddAt(2, NumberColumn)
        End Sub 'Page_Init
        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)
                'Remove from Cart.
                CartView.RowFilter = "Item='" & item & "'"
                If CartView.Count > 0 Then
                    CartView.Delete(0)
                End If
                CartView.RowFilter = ""
            End If
            ShoppingCart.DataBind()
        End Sub 'Grid_CartCommand 
       </script>
       <form runat=server>
          <h3>DataGrid Columns Example</h3>
          <table cellpadding="5">
             <tr valign="top">
                   <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>
                   <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>
          </table>
       </form>
    </body>
    </html>
    <%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <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; 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 Page_Init(Object sender, EventArgs e) // Create a dynamic column to add to Columns collection. BoundColumn NumberColumn = new BoundColumn(); NumberColumn.HeaderText="Item Number"; NumberColumn.DataField="IntegerValue"; // Add column to Columns collection. ItemsGrid. Columns .AddAt(2, NumberColumn); 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); //Remove from Cart. CartView.RowFilter = "Item='" + item + "'"; if (CartView.Count > 0) CartView.Delete(0); CartView.RowFilter = ""; ShoppingCart.DataBind(); </script> <form runat=server> <h3>DataGrid Columns Example</h3> <table cellpadding="5"> <tr valign="top"> <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> <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> </table> </form> </body> </html>

    [JScript] 
    <%@ Page Language="JScript" AutoEventWireup="True" %>
    <%@ Import Namespace="System.Data" %>
       <script language="JScript" runat="server">
          var Cart : DataTable = new DataTable();
          var CartView : DataView;   
          function CreateDataSource() : ICollection
             var dt : DataTable = new DataTable();
             var dr : DataRow;
             dt.Columns.Add(new DataColumn("IntegerValue", Int32));
             dt.Columns.Add(new DataColumn("StringValue", System.String));
             dt.Columns.Add(new DataColumn("CurrencyValue", double));
             for (var i : int = 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);
             var dv : DataView = new DataView(dt);
             return dv;
          function Page_Load(sender, e : EventArgs) 
             if (Session["DG4_ShoppingCart"] == null) 
                Cart = new DataTable();
                Cart.Columns.Add(new DataColumn("Item", System.String));
                Cart.Columns.Add(new DataColumn("Price", System.String));
                Session["DG4_ShoppingCart"] = Cart;
                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();
          function Page_Init(sender, e : EventArgs) 
             // Create a dynamic column to add to Columns collection.
             var NumberColumn : BoundColumn = new BoundColumn();
             NumberColumn.HeaderText="Item Number"; 
             NumberColumn.DataField="IntegerValue";
             // Add column to Columns collection.
             ItemsGrid.Columns.AddAt(2, NumberColumn);
          function Grid_CartCommand(sender, e : DataGridCommandEventArgs) {
             var dr : 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.
             var itemCell : TableCell = e.Item.Cells[2];
             var priceCell : TableCell = e.Item.Cells[3];
             var item : String = itemCell.Text;
             var price : String = priceCell.Text;
             if ((Button(e.CommandSource)).CommandName == "AddToCart") 
                dr[0] = item;
                dr[1] = price;
                Cart.Rows.Add(dr);
                //Remove from Cart.
                CartView.RowFilter = "Item='" + item + "'";
                if (CartView.Count > 0) 
                   CartView.Delete(0);
                CartView.RowFilter = "";
             ShoppingCart.DataBind();
       </script>
       <form runat=server>
          <h3>DataGrid Columns Example</h3>
          <table cellpadding="5">
             <tr valign="top">
                   <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>
                   <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>
          </table>
       </form>
    </body>
    </html>

    [Visual Basic] 
    <%@ Page Language="VB" AutoEventWireup="True" %>
    <%@ Import Namespace="System.Data" %>
       <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 4 
                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 times.
             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)        
             ' 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
          Sub Check_Change(sender As Object, e As EventArgs)
             ' Show or hide the first column depending on the value of
             ' the check box.
             If ShowCheckBox.Checked Then
                ItemsGrid.Columns(0).Visible = True
                ItemsGrid.Columns(0).Visible = False
             End If
          End Sub
       </script>
       <form runat=server>
          <h3>DataGridColumn Visible Example</h3>
          Select whether to show or hide the first column.
          <br><br>
          <b>Product List</b>
          <asp:DataGrid id="ItemsGrid"
               BorderColor="black"
               BorderWidth="1"
               CellPadding="3"
               ShowFooter="True"
               AutoGenerateColumns="False"
               runat="server">
             <HeaderStyle BackColor="#00aaaa">
             </HeaderStyle>
             <FooterStyle BackColor="#00aaaa">
             </FooterStyle>
             <Columns>
                <asp:BoundColumn DataField="IntegerValue"
                     Visible="True" 
                     HeaderText="Item"/>
                <asp:BoundColumn DataField="StringValue"
                     Visible="True"  
                     HeaderText="Description"/>
                <asp:BoundColumn DataField="CurrencyValue"
                     Visible="True"  
                     HeaderText="Price"
                     DataFormatString="{0:c}">
                   <ItemStyle HorizontalAlign="Right">
                   </ItemStyle>
                </asp:BoundColumn>
                <asp:TemplateColumn HeaderText="Select Item"
                     Visible="True" >
                   <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"/>
          <asp:CheckBox id="ShowCheckBox"
               Text="Show first column"
               AutoPostBack="True"
               OnCheckedChanged="Check_Change"
               Checked="True"
               runat="server"/>
       </form>
    </body>
    </html>
    <%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <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 < 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) // 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++; void Check_Change(Object sender, EventArgs e) // Show or hide the first column depending on the value of // the check box. if (ShowCheckBox.Checked) ItemsGrid. Columns [0].Visible = true; ItemsGrid. Columns [0].Visible = false; </script> <form runat=server> <h3>DataGridColumn Visible Example</h3> Select whether to show or hide the first column. <br><br> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" ShowFooter="True" AutoGenerateColumns="False" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <FooterStyle BackColor="#00aaaa"> </FooterStyle> < Columns > <asp:BoundColumn DataField="IntegerValue" Visible="True" HeaderText="Item"/> <asp:BoundColumn DataField="StringValue" Visible="True" HeaderText="Description"/> <asp:BoundColumn DataField="CurrencyValue" Visible="True" HeaderText="Price" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"> </ItemStyle> </asp:BoundColumn> <asp:TemplateColumn HeaderText="Select Item" Visible="True" > <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"/> <asp:CheckBox id="ShowCheckBox" Text="Show first column" AutoPostBack="True" OnCheckedChanged="Check_Change" Checked="True" runat="server"/> </form> </body> </html>

    [C++] 没有可用于 C++ 的示例。若要查看 Visual Basic、C# 或 JScript 示例,请单击页左上角的“语言筛选器”按钮 语言筛选器

    平台: Windows 2000, Windows XP Professional, Windows Server 2003 系列

    DataGrid 类 | DataGrid 成员 | System.Web.UI.WebControls 命名空间 | DataGridColumn | BoundColumn | ButtonColumn | EditCommandColumn | HyperLinkColumn | TemplateColumn | DataGrid 成员(Visual J# 语法) | C++ 托管扩展编程

    发送有关此主题的意见

    © 2001-2002 Microsoft Corporation。保留所有权利。

  •