DataGridColumnCollection 類別

定義

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
繼承
DataGridColumnCollection
實作

範例

下列程式碼範例示範如何使用 DataGridColumnCollection 集合,以動態方式將資料行加入至 DataGrid 控制項。The following code example demonstrates how to use the DataGridColumnCollection collection to dynamically add a column to the DataGrid control. 請注意, Columns 控制項的屬性 DataGrid 是類別的實例 DataGridColumnCollectionNote 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>

備註

DataGridColumnCollection 可以使用集合,以程式設計方式管理衍生的資料 DataGridColumn 行物件集合。Use the DataGridColumnCollection collection to programmatically manage a collection of DataGridColumn-derived column objects. 這些物件代表控制項中的資料行 DataGridThese objects represent the columns in a DataGrid control. 您可以在集合中加入、移除或插入資料行 DataGridColumnCollectionYou can add, remove, or insert columns in the DataGridColumnCollection collection.

注意

AutoGenerateColumns 屬性設定為控制項所 true, 建立的資料行時, DataGrid 不會加入至 Columns 集合中。When the AutoGenerateColumns property is set to true, the columns created by the DataGrid control are not added to the Columns collection.

DataGrid控制項不會將其集合的內容儲存 Columns 在 view 狀態中。The 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 控制項顯示時,不會在控制項中反映集合的變更 DataGridOtherwise, 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.

集合中資料行的順序會決定資料行在控制項中的顯示順序 DataGridThe order of the columns in the collection determines the order that the columns are displayed in the DataGrid control.

下表列出衍生自類別的不同資料行類別 DataGridColumnThe following table lists the different column classes that derive from the DataGridColumn class.

Column 類別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. 這是控制項的預設資料行類型 DataGridThis 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. 它不會直接在集合中使用 DataGridColumnCollectionIt is not used directly in the DataGridColumnCollection collection.

建構函式

DataGridColumnCollection(DataGrid, ArrayList)

初始化 DataGridColumnCollection 類別的新執行個體。Initializes a new instance of the DataGridColumnCollection class.

屬性

Count

取得 DataGridColumnCollection 集合中的資料行數目。Gets the number of columns in the DataGridColumnCollection collection.

IsReadOnly

取得值,指出是否可以修改 DataGridColumnCollection 集合中的資料行。Gets a value that indicates whether the columns in the DataGridColumnCollection collection can be modified.

IsSynchronized

取得值,指出對 DataGridColumnCollection 集合的存取是否為同步 (具備執行緒安全)。Gets a value indicating whether access to the DataGridColumnCollection collection is synchronized (thread safe).

Item[Int32]

DataGridColumn 集合中指定的索引處,取得 DataGridColumnCollection 衍生資料行物件。Gets a DataGridColumn-derived column object from the DataGridColumnCollection collection at the specified index.

SyncRoot

取得可用來同步存取 DataGridColumnCollection 集合的物件。Gets the object that can be used to synchronize access to the DataGridColumnCollection collection.

方法

Add(DataGridColumn)

將指定之 DataGridColumn 衍生資料行物件附加至 DataGridColumnCollection 集合的結尾。Appends the specified DataGridColumn-derived column object to the end of the DataGridColumnCollection collection.

AddAt(Int32, DataGridColumn)

DataGridColumn 衍生資料行物件插入 DataGridColumnCollection 集合中指定的索引處。Inserts a DataGridColumn-derived column object in the DataGridColumnCollection collection at the specified index.

Clear()

DataGridColumn 集合移除所有 DataGridColumnCollection 衍生資料行物件。Removes all DataGridColumn-derived column objects from the DataGridColumnCollection collection.

CopyTo(Array, Int32)

DataGridColumnCollection 中指定的索引處開始,將項目從 Array 集合複製到指定的 ArrayCopies the items from the DataGridColumnCollection collection to the specified Array, starting at the specified index in the Array.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetEnumerator()

傳回 IEnumerator 介面,包含 DataGridColumn 集合中所有 DataGridColumnCollection 衍生資料行物件。Returns a IEnumerator interface that contains all the DataGridColumn-derived column objects in the DataGridColumnCollection collection.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
IndexOf(DataGridColumn)

DataGridColumn 集合傳回指定之 DataGridColumnCollection 衍生資料行物件的索引。Returns the index of the specified DataGridColumn-derived column object from the DataGridColumnCollection collection.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
Remove(DataGridColumn)

DataGridColumn 集合移除指定的 DataGridColumnCollection 衍生資料行物件。Removes the specified DataGridColumn-derived column object from the DataGridColumnCollection collection.

RemoveAt(Int32)

DataGridColumn 集合中指定的索引處,移除 DataGridColumnCollection 衍生資料行物件。Removes a DataGridColumn-derived column object from the DataGridColumnCollection collection at the specified index.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IStateManager.IsTrackingViewState

取得值,指出集合是否正在追蹤它的檢視狀態變更。Gets a value indicating whether the collection is tracking its view-state changes.

IStateManager.LoadViewState(Object)

載入先前儲存的狀態。Loads the previously saved state.

IStateManager.SaveViewState()

傳回包含狀態變更的物件。Returns an object containing state changes.

IStateManager.TrackViewState()

啟動追蹤狀態的變更。Starts tracking state changes.

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

另請參閱