DataGridColumnCollection DataGridColumnCollection DataGridColumnCollection DataGridColumnCollection Class

定义

DataGridColumn 派生的列对象的集合,这些对象表示 DataGrid 控件中的列。A collection of DataGridColumn-derived column objects that represent the columns in a DataGrid control. 此类不能被继承。This class cannot be inherited.

public ref class DataGridColumnCollection sealed : System::Collections::ICollection, System::Web::UI::IStateManager
public sealed class DataGridColumnCollection : System.Collections.ICollection, System.Web.UI.IStateManager
type DataGridColumnCollection = class
    interface ICollection
    interface IEnumerable
    interface IStateManager
Public NotInheritable Class DataGridColumnCollection
Implements ICollection, IStateManager
继承
DataGridColumnCollectionDataGridColumnCollectionDataGridColumnCollectionDataGridColumnCollection
实现

示例

下面的代码示例演示如何使用DataGridColumnCollection集合将列动态添加DataGrid到控件。The following code example demonstrates how to use the DataGridColumnCollection collection to dynamically add a column to the DataGrid control. 请注意, Columns DataGrid控件的属性DataGridColumnCollection为类的实例。Note that the Columns property of the DataGrid control is an instance of the DataGridColumnCollection class.


<%@ Page Language="C#" 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">

      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) 
      {

         // Create a DataGrid control.
         DataGrid ItemsGrid = new DataGrid();

         // Set the properties of the DataGrid.
         ItemsGrid.ID = "ItemsGrid";
         ItemsGrid.BorderColor = System.Drawing.Color.Black;
         ItemsGrid.CellPadding = 3;
         ItemsGrid.AutoGenerateColumns = false;

         // Set the styles for the DataGrid.
         ItemsGrid.HeaderStyle.BackColor = 
             System.Drawing.Color.FromArgb(0x0000aaaa);

         // Create the columns for the DataGrid control. The DataGrid
         // columns are dynamically generated. Therefore, the columns   
         // must be re-created each time the page is refreshed.
         
         // Create and add the columns to the collection.
         ItemsGrid.Columns.Add(CreateBoundColumn("IntegerValue", "Item"));
         ItemsGrid.Columns.Add(
             CreateBoundColumn("StringValue", "Description"));
         ItemsGrid.Columns.Add(
             CreateBoundColumn("CurrencyValue", "Price", "{0:c}", 
             HorizontalAlign.Right));
         ItemsGrid.Columns.Add(
             CreateLinkColumn("http://www.microsoft.com", "_self", 
             "Microsoft", "Related link"));
        
         // Specify the data source and bind it to the control.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();

         // Add the DataGrid control to the Controls collection of 
         // the PlaceHolder control.
         Place.Controls.Add(ItemsGrid);

      }

      BoundColumn CreateBoundColumn(String DataFieldValue, 
          String HeaderTextValue)
      {

         // This version of the CreateBoundColumn method sets only the
         // DataField and HeaderText properties.

         // Create a BoundColumn.
         BoundColumn column = new BoundColumn();

         // Set the properties of the BoundColumn.
         column.DataField = DataFieldValue;
         column.HeaderText = HeaderTextValue;

         return column;

      }

      BoundColumn CreateBoundColumn(String DataFieldValue, 
          String HeaderTextValue, String FormatValue, 
          HorizontalAlign AlignValue)
      {

         // This version of CreateBoundColumn method sets the DataField,
         // HeaderText, and DataFormatString properties. It also sets the 
         // HorizontalAlign property of the ItemStyle property of the column. 

         // Create a BoundColumn using the overloaded CreateBoundColumn method.
         BoundColumn column = CreateBoundColumn(DataFieldValue, HeaderTextValue);

         // Set the properties of the BoundColumn.
         column.DataFormatString = FormatValue;
         column.ItemStyle.HorizontalAlign = AlignValue;

         return column;

      }

      HyperLinkColumn CreateLinkColumn(String NavUrlValue, 
          String TargetValue, String TextValue, String HeaderTextValue)
      {

         // Create a BoundColumn.
         HyperLinkColumn column = new HyperLinkColumn();

         // Set the properties of the ButtonColumn.
         column.NavigateUrl = NavUrlValue;
         column.Target = TargetValue;
         column.Text = TextValue;
         column.HeaderText = HeaderTextValue;

         return column;

      }

   </script>
 
<head runat="server">
    <title>DataGrid Constructor Example</title>
</head>
<body>
 
   <form id="form1" runat="server">
 
      <h3>DataGrid Constructor Example</h3>
 
      <b>Product List</b>

      <asp:PlaceHolder id="Place"
           runat="server"/>
 
   </form>
 
</body>
</html>


<%@ Page Language="VB" 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() 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) 

         ' Create a DataGrid control.
         Dim ItemsGrid As DataGrid = New DataGrid()

         ' Set the properties of the DataGrid.
         ItemsGrid.ID = "ItemsGrid"
         ItemsGrid.BorderColor = System.Drawing.Color.Black
         ItemsGrid.CellPadding = 3
         ItemsGrid.AutoGenerateColumns = False

         ' Set the styles for the DataGrid.
         ItemsGrid.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(&H0000aaaa)

         ' Create the columns for the DataGrid control. The DataGrid
         ' columns are dynamically generated. Therefore, the columns   
         ' must be re-created each time the page is refreshed.
         
         ' Create and add the columns to the collection.
         ItemsGrid.Columns.Add(CreateBoundColumn("IntegerValue", "Item"))
         ItemsGrid.Columns.Add( _
             CreateBoundColumn("StringValue", "Description"))
         ItemsGrid.Columns.Add( _
             CreateBoundColumn("CurrencyValue", "Price", "{0:c}", _
             HorizontalAlign.Right))
         ItemsGrid.Columns.Add( _
             CreateLinkColumn("http:'www.microsoft.com", "_self", _
             "Microsoft", "Related link"))
        
         ' Specify the data source and bind it to the control.     
         ItemsGrid.DataSource = CreateDataSource()
         ItemsGrid.DataBind()

         ' Add the DataGrid control to the Controls collection of 
         ' the PlaceHolder control.
         Place.Controls.Add(ItemsGrid)

      End Sub

      Function CreateBoundColumn(DataFieldValue As String, HeaderTextValue As String) As BoundColumn

         ' This version of CreateBoundColumn method sets only the 
         ' DataField and HeaderText properties.

         ' Create a BoundColumn.
         Dim column As BoundColumn = New BoundColumn()

         ' Set the properties of the BoundColumn.
         column.DataField = DataFieldValue
         column.HeaderText = HeaderTextValue

         Return column

      End Function

      Function CreateBoundColumn(DataFieldValue As String, _
          HeaderTextValue As String, FormatValue As String, _
          AlignValue As HorizontalAlign) As BoundColumn

         ' This version of CreateBoundColumn method sets the DataField,
         ' HeaderText, and DataFormatString properties. It also sets the 
         ' HorizontalAlign property of the ItemStyle property of the column. 

         ' Create a BoundColumn using the overloaded CreateBoundColumn method.
         Dim column As BoundColumn = CreateBoundColumn(DataFieldValue, HeaderTextValue)

         ' Set the properties of the BoundColumn.
         column.DataFormatString = FormatValue
         column.ItemStyle.HorizontalAlign = AlignValue

         Return column

      End Function

      Function CreateLinkColumn(NavUrlValue As String, TargetValue As String, _
         TextValue As String, HeaderTextValue As String) As HyperLinkColumn 

         ' Create a BoundColumn.
         Dim column As HyperLinkColumn = New HyperLinkColumn()

         ' Set the properties of the ButtonColumn.
         column.NavigateUrl = NavUrlValue
         column.Target = TargetValue
         column.Text = TextValue
         column.HeaderText = HeaderTextValue

         Return column

      End Function

   </script>
 
<head runat="server">
    <title>DataGrid Constructor Example</title>
</head>
<body>
 
   <form id="form1" runat="server">
 
      <h3>DataGrid Constructor Example</h3>
 
      <b>Product List</b>

      <asp:PlaceHolder id="Place"
           runat="server"/>
 
   </form>
 
</body>
</html>

注解

使用集合以编程方式管理派生列对象DataGridColumn的集合。 DataGridColumnCollectionUse the DataGridColumnCollection collection to programmatically manage a collection of DataGridColumn-derived column objects. 这些对象表示DataGrid控件中的列。These objects represent the columns in a DataGrid control. 您可以在DataGridColumnCollection集合中添加、删除或插入列。You can add, remove, or insert columns in the DataGridColumnCollection collection.

备注

当属性设置为true,时, DataGrid控件创建的列不会添加到Columns集合中。 AutoGenerateColumnsWhen the AutoGenerateColumns property is set to true, the columns created by the DataGrid control are not added to the Columns collection.

控件不会将其Columns集合的内容存储在视图状态中。 DataGridThe DataGrid control does not store the contents of its Columns collection in the view state. 若要动态添加或删除列, 您必须在每次刷新页面时以编程方式添加或删除列。To add or remove a column dynamically, you must programmatically add or remove the column every time the page is refreshed. 提供一个Page_Init函数, 该函数在重新加载DataGrid控件状态并重新生成控件之前添加或移除列。Provide a Page_Init function that adds or removes the column before the DataGrid control's state is reloaded and the control is rebuilt. 否则, 在显示Columns集合时, 对集合所做的更改不会反映DataGrid在控件中。Otherwise, the changes to the Columns collection are not reflected in the DataGrid control when it is displayed.

备注

虽然您可以通过编程方式向Columns DataGrid控件的集合中添加列或从中删除列, 但使用Visible静态方式列出列会更容易, 并使用属性来显示或隐藏每个列。Although you can programmatically add columns to or remove columns from the Columns collection of the DataGrid control, it is easier to list the columns statically and then use the Visible property to display or hide each column.

集合中列的顺序决定了列在DataGrid控件中的显示顺序。The order of the columns in the collection determines the order that the columns are displayed in the DataGrid control.

下表列出了从DataGridColumn类派生的不同列类。The following table lists the different column classes that derive from the DataGridColumn class.

列类Column Class 说明Description
BoundColumn 绑定到数据源中的字段的列。A column that is bound to a field in a data source. 它将字段中的每个项显示为文本。It displays each item in the field as text. 这是DataGrid控件的默认列类型。This is the default column type for the DataGrid control.
ButtonColumn 显示列中每一项的命令按钮的列。A column that 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 包含列中每一项的编辑命令的列。A column that contains editing commands for each item in the column.
HyperLinkColumn 将列中的每一项显示为超链接的列。A column that displays each item in the column as a hyperlink. 列的内容可以绑定到数据源中的字段或静态文本。The contents of the column can be bound to a field in a data source, or to static text.
TemplateColumn 根据指定的模板显示列中的每一项的列。A column that displays each item in the column according to a specified template. 这允许您控制列的内容, 例如显示图像。This allows you to control the content of the column, for example to display images.

备注

DataGridColumn类是列出的列类的基类。The DataGridColumn class is the base class for the column classes listed. 它不会在DataGridColumnCollection集合中直接使用。It is not used directly in the DataGridColumnCollection collection.

构造函数

DataGridColumnCollection(DataGrid, ArrayList) DataGridColumnCollection(DataGrid, ArrayList) DataGridColumnCollection(DataGrid, ArrayList) DataGridColumnCollection(DataGrid, ArrayList)

初始化 DataGridColumnCollection 类的新实例。Initializes a new instance of the DataGridColumnCollection class.

属性

Count Count Count Count

获取 DataGridColumnCollection 集合中列的数目。Gets the number of columns in the DataGridColumnCollection collection.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

获取一个值,该值指示 DataGridColumnCollection 集合中的列是否可被修改。Gets a value that indicates whether the columns in the DataGridColumnCollection collection can be modified.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

获取一个值,该值指示对 DataGridColumnCollection 集合的访问是否同步(线程安全)。Gets a value indicating whether access to the DataGridColumnCollection collection is synchronized (thread safe).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

获取 DataGridColumn 集合中指定索引位置处的由 DataGridColumnCollection 导出的列对象。Gets a DataGridColumn-derived column object from the DataGridColumnCollection collection at the specified index.

SyncRoot SyncRoot SyncRoot SyncRoot

获取可用于同步 DataGridColumnCollection 集合访问的对象。Gets the object that can be used to synchronize access to the DataGridColumnCollection collection.

方法

Add(DataGridColumn) Add(DataGridColumn) Add(DataGridColumn) Add(DataGridColumn)

将指定的由 DataGridColumn 导出的列对象追加到 DataGridColumnCollection 集合的结尾。Appends the specified DataGridColumn-derived column object to the end of the DataGridColumnCollection collection.

AddAt(Int32, DataGridColumn) AddAt(Int32, DataGridColumn) AddAt(Int32, DataGridColumn) AddAt(Int32, DataGridColumn)

将由 DataGridColumn 导出的列对象插入到 DataGridColumnCollection 集合中的指定索引位置处。Inserts a DataGridColumn-derived column object in the DataGridColumnCollection collection at the specified index.

Clear() Clear() Clear() Clear()

DataGridColumn 集合中移除所有由 DataGridColumnCollection 导出的列对象。Removes all DataGridColumn-derived column objects from the DataGridColumnCollection collection.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

DataGridColumnCollection 集合中的项复制到指定的 Array,从 Array 中的指定索引处开始。Copies the items from the DataGridColumnCollection collection to the specified Array, starting at the specified index in the Array.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回 IEnumerator 接口,该接口包含 DataGridColumn 集合中所有由 DataGridColumnCollection 导出的列对象。Returns a IEnumerator interface that contains all the DataGridColumn-derived column objects in the DataGridColumnCollection collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
IndexOf(DataGridColumn) IndexOf(DataGridColumn) IndexOf(DataGridColumn) IndexOf(DataGridColumn)

返回 DataGridColumn 集合中指定的、由 DataGridColumnCollection 导出的列对象的索引。Returns the index of the specified DataGridColumn-derived column object from the DataGridColumnCollection collection.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(DataGridColumn) Remove(DataGridColumn) Remove(DataGridColumn) Remove(DataGridColumn)

DataGridColumn 集合中移除指定的、由 DataGridColumnCollection 导出的列对象。Removes the specified DataGridColumn-derived column object from the DataGridColumnCollection collection.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

移除 DataGridColumn 集合中指定索引位置处由 DataGridColumnCollection 导出的列对象。Removes a DataGridColumn-derived column object from the DataGridColumnCollection collection at the specified index.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

IStateManager.IsTrackingViewState IStateManager.IsTrackingViewState IStateManager.IsTrackingViewState IStateManager.IsTrackingViewState

获取一个值,该值指示集合是否在跟踪其视图状态的更改。Gets a value indicating whether the collection is tracking its view-state changes.

IStateManager.LoadViewState(Object) IStateManager.LoadViewState(Object) IStateManager.LoadViewState(Object) IStateManager.LoadViewState(Object)

加载以前保存的状态。Loads the previously saved state.

IStateManager.SaveViewState() IStateManager.SaveViewState() IStateManager.SaveViewState() IStateManager.SaveViewState()

返回包含状态更改的对象。Returns an object containing state changes.

IStateManager.TrackViewState() IStateManager.TrackViewState() IStateManager.TrackViewState() IStateManager.TrackViewState()

开始跟踪状态更改。Starts tracking state changes.

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

另请参阅