Partager via


DataGridColumnCollection Classe

Définition

Collection d’objets de DataGridColumncolonne dérivés qui représentent les colonnes d’un DataGrid contrôle. Cette classe ne peut pas être héritée.

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
Héritage
DataGridColumnCollection
Implémente

Exemples

L’exemple de code suivant montre comment utiliser la DataGridColumnCollection collection pour ajouter dynamiquement une colonne au DataGrid contrôle. Notez que la Columns propriété du DataGrid contrôle est une instance de la DataGridColumnCollection classe.


<%@ 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>

Remarques

Utilisez la DataGridColumnCollection collection pour gérer par programmation une collection d’objets de DataGridColumncolonne dérivés. Ces objets représentent les colonnes d’un DataGrid contrôle. Vous pouvez ajouter, supprimer ou insérer des colonnes dans la DataGridColumnCollection collection.

Note

Lorsque la AutoGenerateColumns propriété est définie sur true, les colonnes créées par le DataGrid contrôle ne sont pas ajoutées à la Columns collection.

Le DataGrid contrôle ne stocke pas le contenu de sa Columns collection dans l’état d’affichage. Pour ajouter ou supprimer une colonne dynamiquement, vous devez ajouter ou supprimer la colonne par programmation chaque fois que la page est actualisée. Fournissez une Page_Init fonction qui ajoute ou supprime la colonne avant DataGrid le rechargement de l’état du contrôle et la reconstruction du contrôle. Sinon, les modifications apportées à la Columns collection ne sont pas reflétées dans le DataGrid contrôle lorsqu’elle est affichée.

Note

Bien que vous puissiez ajouter ou supprimer des colonnes par programmation de la ColumnsDataGrid collection du contrôle, il est plus facile de répertorier les colonnes de manière statique, puis d’utiliser la Visible propriété pour afficher ou masquer chaque colonne.

L’ordre des colonnes de la collection détermine l’ordre dans lequel les colonnes sont affichées dans le DataGrid contrôle.

Le tableau suivant répertorie les différentes classes de colonnes qui dérivent de la DataGridColumn classe.

Column, classe Description
BoundColumn Colonne liée à un champ dans une source de données. Il affiche chaque élément dans le champ sous forme de texte. Il s’agit du type de colonne par défaut pour le DataGrid contrôle.
ButtonColumn Colonne qui affiche un bouton de commande pour chaque élément de la colonne. Cela vous permet de créer une colonne de contrôles de bouton personnalisés, tels que ajouter ou supprimer des boutons.
EditCommandColumn Colonne qui contient des commandes de modification pour chaque élément de la colonne.
HyperLinkColumn Colonne qui affiche chaque élément de la colonne sous forme de lien hypertexte. Le contenu de la colonne peut être lié à un champ d’une source de données ou à du texte statique.
TemplateColumn Colonne qui affiche chaque élément de la colonne en fonction d’un modèle spécifié. Cela vous permet de contrôler le contenu de la colonne, par exemple pour afficher des images.

Note

La DataGridColumn classe est la classe de base pour les classes de colonne répertoriées. Elle n’est pas utilisée directement dans la DataGridColumnCollection collection.

Constructeurs

Nom Description
DataGridColumnCollection(DataGrid, ArrayList)

Initialise une nouvelle instance de la classe DataGridColumnCollection.

Propriétés

Nom Description
Count

Obtient le nombre de colonnes de la DataGridColumnCollection collection.

IsReadOnly

Obtient une valeur qui indique si les colonnes de la DataGridColumnCollection collection peuvent être modifiées.

IsSynchronized

Obtient une valeur indiquant si l’accès à la DataGridColumnCollection collection est synchronisé (thread safe).

Item[Int32]

Obtient un DataGridColumnobjet de colonne dérivé de la DataGridColumnCollection collection à l’index spécifié.

SyncRoot

Obtient l’objet qui peut être utilisé pour synchroniser l’accès à la DataGridColumnCollection collection.

Méthodes

Nom Description
Add(DataGridColumn)

Ajoute l’objet de colonne dérivé spécifié DataGridColumnà la fin de la DataGridColumnCollection collection.

AddAt(Int32, DataGridColumn)

Insère un DataGridColumnobjet de colonne dérivé dans la DataGridColumnCollection collection à l’index spécifié.

Clear()

Supprime tous les DataGridColumnobjets de colonne dérivés de la DataGridColumnCollection collection.

CopyTo(Array, Int32)

Copie les éléments de la DataGridColumnCollection collection vers l’index spécifié Array, en commençant à l’index spécifié dans le Array.

Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GetEnumerator()

Retourne une IEnumerator interface qui contient tous les DataGridColumnobjets de colonne dérivés de la DataGridColumnCollection collection.

GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
IndexOf(DataGridColumn)

Retourne l’index de l’objet colonne dérivé spécifié DataGridColumnde la DataGridColumnCollection collection.

MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
Remove(DataGridColumn)

Supprime l’objet de colonne dérivé spécifié DataGridColumnde la DataGridColumnCollection collection.

RemoveAt(Int32)

Supprime un DataGridColumnobjet de colonne dérivé de la DataGridColumnCollection collection à l’index spécifié.

ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)

Implémentations d’interfaces explicites

Nom Description
IStateManager.IsTrackingViewState

Obtient une valeur indiquant si la collection suit ses modifications d’état d’affichage.

IStateManager.LoadViewState(Object)

Charge l’état précédemment enregistré.

IStateManager.SaveViewState()

Retourne un objet contenant les modifications d’état.

IStateManager.TrackViewState()

Démarre le suivi des modifications d’état.

Méthodes d’extension

Nom Description
AsParallel(IEnumerable)

Active la parallélisation d’une requête.

AsQueryable(IEnumerable)

Convertit un IEnumerable en IQueryable.

Cast<TResult>(IEnumerable)

Convertit les éléments d’un IEnumerable en type spécifié.

OfType<TResult>(IEnumerable)

Filtre les éléments d’une IEnumerable en fonction d’un type spécifié.

S’applique à

Voir aussi