DataGrid, classe (System.Windows.Forms)

Bibliothèque de classes .NET Framework 
DataGrid, classe 

Affiche des données ADO.NET dans une grille pouvant faire l'objet d'un défilement. Le contrôle DataGridView remplace et ajoute des fonctionnalités au contrôle DataGrid ; toutefois, le contrôle DataGrid est conservé pour la compatibilité descendante et l'utilisation future si tel est votre choix.

Espace de noms : System.Windows.Forms
Assembly : System.Windows.Forms (dans system.windows.forms.dll)

SyntaxeSyntaxe


Visual Basic (Déclaration)
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
<ComVisibleAttribute(True)> _
Public Class DataGrid
    Inherits Control
    Implements ISupportInitialize, IDataGridEditingService


Visual Basic (Utilisation)
Dim instance As DataGrid


C#
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
[ComVisibleAttribute(true)] 
public class DataGrid : Control, ISupportInitialize, IDataGridEditingService


C++
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] 
[ComVisibleAttribute(true)] 
public ref class DataGrid : public Control, ISupportInitialize, IDataGridEditingService


J#
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
/** @attribute ComVisibleAttribute(true) */ 
public class DataGrid extends Control implements ISupportInitialize, IDataGridEditingService


JScript
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
ComVisibleAttribute(true) 
public class DataGrid extends Control implements ISupportInitialize, IDataGridEditingService
NotesNotes

System.Windows.Forms.DataGrid affiche les liens Web vers les tables enfants. Vous pouvez cliquer sur un lien pour naviguer vers la table enfant. Lorsqu'une table enfant est affichée, un bouton Précédent s'affiche dans la légende ; vous pouvez cliquer dessus pour revenir à la table parente. Les données des lignes parentes sont affichées sous la légende et au-dessus des en-têtes de colonne. Vous pouvez masquer les informations relatives à la ligne parente en cliquant sur le bouton qui se trouve à droite du bouton Précédent.

Pour afficher une table dans le System.Windows.Forms.DataGrid au moment de l'exécution, utilisez la méthode SetDataBinding pour affecter les propriétés DataSource et DataMember à une source de données valide. Les sources de données suivantes sont valides :

Pour plus d'informations sur la classe DataSet, consultez Utilisation de DataSets dans ADO.NET.

Vous pouvez créer une grille qui permet aux utilisateurs de modifier les données, mais qui les empêche d'ajouter de nouvelles lignes, en utilisant DataView comme source de données et en affectant à la propriété AllowNew la valeur false.

Les sources de données sont ensuite managées par les objets BindingManagerBase. Pour chaque table d'une source de données, BindingManagerBase peut être retourné à partir de BindingContext du formulaire. Par exemple, vous pouvez déterminer le nombre de lignes qu'une source de données contient en retournant la propriété BindingManagerBase de l'objet Count associé.

Pour valider les données, utilisez les objets sous-jacents qui représentent les données et leurs événements. Par exemple, si les données proviennent de DataTable dans un DataSet, utilisez les événements ColumnChanging et RowChanging.

RemarqueRemarque

Puisque le nombre de colonnes peut être personnalisé (en ajoutant ou supprimant des membres de GridColumnStylesCollection) et que les lignes peuvent être triées par colonne, il n'est pas garanti que les valeurs des propriétés RowNumber et ColumnNumber correspondent aux index DataRow et DataColumn dans un DataTable. Vous devez par conséquent éviter d'utiliser ces propriétés dans l'événement Validating pour valider les données.

Utilisez la propriété CurrentCell pour déterminer la cellule qui est sélectionnée. Changez la valeur de n'importe quelle cellule en utilisant la propriété Item, qui peut prendre les index de ligne et de colonne de la cellule ou un DataGridCell unique. Surveillez l'événement CurrentCellChanged pour détecter le moment où l'utilisateur sélectionne une autre cellule.

Pour déterminer la partie du contrôle sur laquelle l'utilisateur a cliqué, utilisez la méthode HitTest dans l'événement MouseDown. La méthode HitTest retourne un objet DataGrid.HitTestInfo qui contient la ligne et la colonne d'une zone sur laquelle un clic a été effectué.

Vous disposez de plusieurs propriétés permettant de définir les attributs de couleur et de légende pour gérer l'apparence du contrôle au moment de l'exécution, notamment CaptionForeColor, CaptionBackColor, CaptionFont, etc.

L'apparence de la grille affichée (ou des grilles) peut être modifiée de façon plus détaillée en créant des objets DataGridTableStyle et en les ajoutant à GridTableStylesCollection, accessible par l'intermédiaire de la propriété TableStyles. Par exemple, si un DataSet contenant trois objets DataTable est affecté à DataSource, vous pouvez ajouter trois objets DataGridTableStyle à la collection, un pour chaque table. Pour synchroniser chaque objet DataGridTableStyle avec DataTable, affectez le TableName de DataTable au MappingName de DataGridTableStyle. Pour plus d'informations sur la liaison à un tableau d'objets, consultez la propriété DataGridTableStyle.MappingName.

Pour créer une vue personnalisée d'une table, créez l'instance d'une classe DataGridTextBoxColumn ou DataGridBoolColumn, puis ajoutez l'objet au GridTableStylesCollection accessible via la propriété TableStyles. Les deux classes héritent de DataGridColumnStyle. Pour chaque style de colonne, affectez MappingName au ColumnName d'une colonne à afficher dans la grille. Pour masquer une colonne, affectez une valeur autre qu'un ColumnName valide à MappingName.

Pour mettre en forme le texte d'une colonne, affectez à la propriété Format de DataGridTextBoxColumn l'une des valeurs contenues dans Chaînes de format de date et d'heure ou Chaînes de format numériques standard.

Pour lier DataGrid à un tableau d'objets fortement typé, le type d'objet doit contenir des propriétés publiques. Pour créer un DataGridTableStyle qui affiche un tableau, affectez typename[] à la propriété DataGridTableStyle.MappingName, où typename est remplacé par le nom du type d'objet. Notez également que la propriété MappingName respecte la casse ; le nom de type doit exactement correspondre. Consultez la propriété MappingName pour obtenir un exemple.

Vous pouvez également lier DataGrid à ArrayList. ArrayList a pour caractéristique de pouvoir contenir des objets de plusieurs types, mais DataGrid ne peut se lier à ce type de liste que lorsque tous les éléments de la liste sont du même type que le premier élément. En d'autres termes, tous les objets doivent être du même type ou hériter de la même classe que le premier élément de la liste. Par exemple, si le premier élément d'une liste est Control, le second élément peut être TextBox (qui hérite de Control). Si par contre, le premier élément est TextBox, le second objet ne peut pas être Control. En outre, ArrayList doit contenir des éléments lorsqu'il est lié. Un ArrayList vide produit une grille vide. De plus, les objets dans ArrayList doivent contenir des propriétés publiques. Lors de la liaison à ArrayList, affectez "ArrayList" (nom du type) au MappingName de DataGridTableStyle.

Pour chaque DataGridTableStyle, vous pouvez définir les attributs de couleur et de légende qui substituent les paramètres du contrôle System.Windows.Forms.DataGrid. Cependant, si ces propriétés ne sont pas définies, les paramètres du contrôle sont utilisés par défaut. Les propriétés suivantes peuvent être substituées par les propriétés DataGridTableStyle :

Pour personnaliser l'apparence de chaque colonne, ajoutez les objets DataGridColumnStyle à GridColumnStylesCollection, accessible par l'intermédiaire de la propriété GridColumnStyles de chaque DataGridTableStyle. Pour synchroniser chaque DataGridColumnStyle avec DataColumn dans DataTable, affectez le ColumnName de DataColumn à MappingName. Lors de la construction de DataGridColumnStyle, vous pouvez aussi définir une chaîne de mise en forme qui spécifie la façon dont la colonne affiche les données. Vous pouvez par exemple spécifier que la colonne utilise un format de date courte pour afficher les dates contenues dans la table.

AttentionAttention

Vous devez toujours créer des objets DataGridColumnStyle et les ajouter à GridColumnStylesCollection avant d'ajouter des objets DataGridTableStyle à GridTableStylesCollection. Lorsque vous ajoutez un DataGridTableStyle vide avec une valeur MappingName valide à la collection, des objets DataGridColumnStyle sont automatiquement générés pour vous. Par conséquent, une exception est levée si vous essayez d'ajouter de nouveaux objets DataGridColumnStyle avec des valeurs de MappingName en double à GridColumnStylesCollection.

RemarqueRemarque

Le contrôle DataGridView remplace et ajoute des fonctionnalités au contrôle DataGrid ; toutefois, le contrôle DataGrid est conservé pour la compatibilité descendante et l'utilisation future si tel est votre choix. Pour plus d'informations, consultez Différences entre les contrôles DataGridView et DataGrid Windows Forms.

ExempleExemple

L'exemple de code suivant crée un Windows Form, un DataSet contenant deux objets DataTable et un DataRelation relatif aux deux tables. Pour afficher les données, un contrôle System.Windows.Forms.DataGrid est alors lié à DataSet par l'intermédiaire de la méthode SetDataBinding. Un bouton du formulaire modifie l'apparence de la grille en créant deux objets DataGridTableStyle et en affectant un TableName de l'un des objets DataTable au MappingName de chaque objet. L'exemple contient également du code dans l'événement MouseUp qui utilise la méthode HitTest pour imprimer la colonne, la ligne et la partie de la grille sur laquelle un clic a été effectué.



Visual Basic
Option Explicit
Option Strict

Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
   Inherits System.Windows.Forms.Form
   Private components As System.ComponentModel.Container
   Private button1 As Button
   Private button2 As Button
   Private myDataGrid As DataGrid
   Private myDataSet As DataSet
   Private TablesAlreadyAdded As Boolean    
    
   Public Sub New()
      ' Required for Windows Form Designer support.
      InitializeComponent()
      ' Call SetUp to bind the controls.
      SetUp()
   End Sub 
        
  Private Sub InitializeComponent()
      ' Create the form and its controls.
      Me.components = New System.ComponentModel.Container()
      Me.button1 = New System.Windows.Forms.Button()
      Me.button2 = New System.Windows.Forms.Button()
      Me.myDataGrid = New DataGrid()
      
      Me.Text = "DataGrid Control Sample"
      Me.ClientSize = New System.Drawing.Size(450, 330)
        
      button1.Location = New Point(24, 16)
      button1.Size = New System.Drawing.Size(120, 24)
      button1.Text = "Change Appearance"
      AddHandler button1.Click, AddressOf button1_Click
        
      button2.Location = New Point(150, 16)
      button2.Size = New System.Drawing.Size(120, 24)
      button2.Text = "Get Binding Manager"
      AddHandler button2.Click, AddressOf button2_Click
        
      myDataGrid.Location = New Point(24, 50)
      myDataGrid.Size = New Size(300, 200)
      myDataGrid.CaptionText = "Microsoft DataGrid Control"
      AddHandler myDataGrid.MouseUp, AddressOf Grid_MouseUp
        
      Me.Controls.Add(button1)
      Me.Controls.Add(button2)
      Me.Controls.Add(myDataGrid)
   End Sub 
    
   Public Shared Sub Main()
      Application.Run(New Form1())
   End Sub 
        
   Private Sub SetUp()
      ' Create a DataSet with two tables and one relation.
      MakeDataSet()
      ' Bind the DataGrid to the DataSet. The dataMember
      ' specifies that the Customers table should be displayed.
      myDataGrid.SetDataBinding(myDataSet, "Customers")
   End Sub 
        
    Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If TablesAlreadyAdded = True Then Exit Sub
        AddCustomDataTableStyle()
    End Sub
   
   Private Sub AddCustomDataTableStyle()
      Dim ts1 As New DataGridTableStyle()
      ts1.MappingName = "Customers"
      ' Set other properties.
      ts1.AlternatingBackColor = Color.LightGray
      ' Add a GridColumnStyle and set its MappingName 
      ' to the name of a DataColumn in the DataTable. 
      ' Set the HeaderText and Width properties. 
        
      Dim boolCol As New DataGridBoolColumn()
      boolCol.MappingName = "Current"
      boolCol.HeaderText = "IsCurrent Customer"
      boolCol.Width = 150
      ts1.GridColumnStyles.Add(boolCol)
        
      ' Add a second column style.
      Dim TextCol As New DataGridTextBoxColumn()
      TextCol.MappingName = "custName"
      TextCol.HeaderText = "Customer Name"
      TextCol.Width = 250
      ts1.GridColumnStyles.Add(TextCol)
        
      ' Create the second table style with columns.
      Dim ts2 As New DataGridTableStyle()
      ts2.MappingName = "Orders"
        
      ' Set other properties.
      ts2.AlternatingBackColor = Color.LightBlue
        
      ' Create new ColumnStyle objects
      Dim cOrderDate As New DataGridTextBoxColumn()
      cOrderDate.MappingName = "OrderDate"
      cOrderDate.HeaderText = "Order Date"
      cOrderDate.Width = 100
      ts2.GridColumnStyles.Add(cOrderDate)

      ' Use a PropertyDescriptor to create a formatted
      ' column. First get the PropertyDescriptorCollection
      ' for the data source and data member. 
      Dim pcol As PropertyDescriptorCollection = _
      Me.BindingContext(myDataSet, "Customers.custToOrders"). _
      GetItemProperties()

      ' Create a formatted column using a PropertyDescriptor.
      ' The formatting character "c" specifies a currency format. */     
        
      Dim csOrderAmount As _
      New DataGridTextBoxColumn(pcol("OrderAmount"), "c", True)
      csOrderAmount.MappingName = "OrderAmount"
      csOrderAmount.HeaderText = "Total"
      csOrderAmount.Width = 100
      ts2.GridColumnStyles.Add(csOrderAmount)
        
      ' Add the DataGridTableStyle instances to 
      ' the GridTableStylesCollection. 
      myDataGrid.TableStyles.Add(ts1)
      myDataGrid.TableStyles.Add(ts2)

     ' Sets the TablesAlreadyAdded to true so this doesn't happen again.
      TablesAlreadyAdded = true
   End Sub 
    
    Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim bmGrid As BindingManagerBase
        bmGrid = BindingContext(myDataSet, "Customers")
        MessageBox.Show(("Current BindingManager Position: " & bmGrid.Position))
    End Sub
        
   Private Sub Grid_MouseUp(sender As Object, e As MouseEventArgs)
      ' Create a HitTestInfo object using the HitTest method.
      ' Get the DataGrid by casting sender.
      Dim myGrid As DataGrid = CType(sender, DataGrid)
      Dim myHitInfo As DataGrid.HitTestInfo = myGrid.HitTest(e.X, e.Y)
      Console.WriteLine(myHitInfo)
      Console.WriteLine(myHitInfo.Type)
      Console.WriteLine(myHitInfo.Row)
      Console.WriteLine(myHitInfo.Column)
   End Sub 
        
   ' Create a DataSet with two tables and populate it.
   Private Sub MakeDataSet()
      ' Create a DataSet.
      myDataSet = New DataSet("myDataSet")
       
      ' Create two DataTables.
      Dim tCust As New DataTable("Customers")
      Dim tOrders As New DataTable("Orders")
      
      ' Create two columns, and add them to the first table.
      Dim cCustID As New DataColumn("CustID", GetType(Integer))
      Dim cCustName As New DataColumn("CustName")
      Dim cCurrent As New DataColumn("Current", GetType(Boolean))
      tCust.Columns.Add(cCustID)
      tCust.Columns.Add(cCustName)
      tCust.Columns.Add(cCurrent)
       
      ' Create three columns, and add them to the second table.
      Dim cID As New DataColumn("CustID", GetType(Integer))
      Dim cOrderDate As New DataColumn("orderDate", GetType(DateTime))
      Dim cOrderAmount As New DataColumn("OrderAmount", GetType(Decimal))
      tOrders.Columns.Add(cOrderAmount)
      tOrders.Columns.Add(cID)
      tOrders.Columns.Add(cOrderDate)
       
      ' Add the tables to the DataSet.
      myDataSet.Tables.Add(tCust)
      myDataSet.Tables.Add(tOrders)
        
      ' Create a DataRelation, and add it to the DataSet.
      Dim dr As New DataRelation("custToOrders", cCustID, cID)
      myDataSet.Relations.Add(dr)
        
      ' Populates the tables. For each customer and order, 
      ' creates two DataRow variables. 
      Dim newRow1 As DataRow
      Dim newRow2 As DataRow
        
      ' Create three customers in the Customers Table.
      Dim i As Integer
      For i = 1 To 3
         newRow1 = tCust.NewRow()
         newRow1("custID") = i
         ' Add the row to the Customers table.
         tCust.Rows.Add(newRow1)
      Next i
      ' Give each customer a distinct name.
      tCust.Rows(0)("custName") = "Customer1"
      tCust.Rows(1)("custName") = "Customer2"
      tCust.Rows(2)("custName") = "Customer3"
        
      ' Give the Current column a value.
      tCust.Rows(0)("Current") = True
      tCust.Rows(1)("Current") = True
      tCust.Rows(2)("Current") = False
        
      ' For each customer, create five rows in the Orders table.
      For i = 1 To 3
         Dim j As Integer
         For j = 1 To 5
            newRow2 = tOrders.NewRow()
            newRow2("CustID") = i
            newRow2("orderDate") = New DateTime(2001, i, j * 2)
            newRow2("OrderAmount") = i * 10 + j * 0.1
            ' Add the row to the Orders table.
            tOrders.Rows.Add(newRow2)
         Next j
      Next i
   End Sub 
End Class 


C#
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
   private System.ComponentModel.Container components;
   private Button button1;
   private Button button2;
   private DataGrid myDataGrid;   
   private DataSet myDataSet;
   private bool TablesAlreadyAdded;
   public Form1()
   {
      // Required for Windows Form Designer support.
      InitializeComponent();
      // Call SetUp to bind the controls.
      SetUp();
   }

   protected override void Dispose( bool disposing ){
      if( disposing ){
         if (components != null){
            components.Dispose();}
      }
      base.Dispose( disposing );
   }
   private void InitializeComponent()
   {
      // Create the form and its controls.
      this.components = new System.ComponentModel.Container();
      this.button1 = new System.Windows.Forms.Button();
      this.button2 = new System.Windows.Forms.Button();
      this.myDataGrid = new DataGrid();
      
      this.Text = "DataGrid Control Sample";
      this.ClientSize = new System.Drawing.Size(450, 330);
      
      button1.Location = new Point(24, 16);
      button1.Size = new System.Drawing.Size(120, 24);
      button1.Text = "Change Appearance";
      button1.Click+=new System.EventHandler(button1_Click);

      button2.Location = new Point(150, 16);
      button2.Size = new System.Drawing.Size(120, 24);
      button2.Text = "Get Binding Manager";
      button2.Click+=new System.EventHandler(button2_Click);

      myDataGrid.Location = new  Point(24, 50);
      myDataGrid.Size = new Size(300, 200);
      myDataGrid.CaptionText = "Microsoft DataGrid Control";
      myDataGrid.MouseUp += new MouseEventHandler(Grid_MouseUp);
      
      this.Controls.Add(button1);
      this.Controls.Add(button2);
      this.Controls.Add(myDataGrid);
   }

   public static void Main()
   {
      Application.Run(new Form1());
   }
   
   private void SetUp()
   {
      // Create a DataSet with two tables and one relation.
      MakeDataSet();
      /* Bind the DataGrid to the DataSet. The dataMember
      specifies that the Customers table should be displayed.*/
      myDataGrid.SetDataBinding(myDataSet, "Customers");
   }

   private void button1_Click(object sender, System.EventArgs e)
   {
      if(TablesAlreadyAdded) return;
      AddCustomDataTableStyle();
   }

   private void AddCustomDataTableStyle()
   {
      DataGridTableStyle ts1 = new DataGridTableStyle();
      ts1.MappingName = "Customers";
      // Set other properties.
      ts1.AlternatingBackColor = Color.LightGray;

      /* Add a GridColumnStyle and set its MappingName 
      to the name of a DataColumn in the DataTable. 
      Set the HeaderText and Width properties. */
      
      DataGridColumnStyle boolCol = new DataGridBoolColumn();
      boolCol.MappingName = "Current";
      boolCol.HeaderText = "IsCurrent Customer";
      boolCol.Width = 150;
      ts1.GridColumnStyles.Add(boolCol);
      
      // Add a second column style.
      DataGridColumnStyle TextCol = new DataGridTextBoxColumn();
      TextCol.MappingName = "custName";
      TextCol.HeaderText = "Customer Name";
      TextCol.Width = 250;
      ts1.GridColumnStyles.Add(TextCol);

      // Create the second table style with columns.
      DataGridTableStyle ts2 = new DataGridTableStyle();
      ts2.MappingName = "Orders";

      // Set other properties.
      ts2.AlternatingBackColor = Color.LightBlue;
      
      // Create new ColumnStyle objects
      DataGridColumnStyle cOrderDate = 
      new DataGridTextBoxColumn();
      cOrderDate.MappingName = "OrderDate";
      cOrderDate.HeaderText = "Order Date";
      cOrderDate.Width = 100;
      ts2.GridColumnStyles.Add(cOrderDate);

      /* Use a PropertyDescriptor to create a formatted
      column. First get the PropertyDescriptorCollection
      for the data source and data member. */
      PropertyDescriptorCollection pcol = this.BindingContext
      [myDataSet, "Customers.custToOrders"].GetItemProperties();
 
      /* Create a formatted column using a PropertyDescriptor.
      The formatting character "c" specifies a currency format. */     
      DataGridColumnStyle csOrderAmount = 
      new DataGridTextBoxColumn(pcol["OrderAmount"], "c", true);
      csOrderAmount.MappingName = "OrderAmount";
      csOrderAmount.HeaderText = "Total";
      csOrderAmount.Width = 100;
      ts2.GridColumnStyles.Add(csOrderAmount);

      /* Add the DataGridTableStyle instances to 
      the GridTableStylesCollection. */
      myDataGrid.TableStyles.Add(ts1);
      myDataGrid.TableStyles.Add(ts2);

     // Sets the TablesAlreadyAdded to true so this doesn't happen again.
     TablesAlreadyAdded=true;
   }

   private void button2_Click(object sender, System.EventArgs e)
   {
      BindingManagerBase bmGrid;
      bmGrid = BindingContext[myDataSet, "Customers"];
      MessageBox.Show("Current BindingManager Position: " + bmGrid.Position);
   }

   private void Grid_MouseUp(object sender, MouseEventArgs e)
   {
      // Create a HitTestInfo object using the HitTest method.

      // Get the DataGrid by casting sender.
      DataGrid myGrid = (DataGrid)sender;
      DataGrid.HitTestInfo myHitInfo = myGrid.HitTest(e.X, e.Y);
      Console.WriteLine(myHitInfo);
      Console.WriteLine(myHitInfo.Type);
      Console.WriteLine(myHitInfo.Row);
      Console.WriteLine(myHitInfo.Column);
   }

   // Create a DataSet with two tables and populate it.
   private void MakeDataSet()
   {
      // Create a DataSet.
      myDataSet = new DataSet("myDataSet");
      
      // Create two DataTables.
      DataTable tCust = new DataTable("Customers");
      DataTable tOrders = new DataTable("Orders");

      // Create two columns, and add them to the first table.
      DataColumn cCustID = new DataColumn("CustID", typeof(int));
      DataColumn cCustName = new DataColumn("CustName");
      DataColumn cCurrent = new DataColumn("Current", typeof(bool));
      tCust.Columns.Add(cCustID);
      tCust.Columns.Add(cCustName);
      tCust.Columns.Add(cCurrent);

      // Create three columns, and add them to the second table.
      DataColumn cID = 
      new DataColumn("CustID", typeof(int));
      DataColumn cOrderDate = 
      new DataColumn("orderDate",typeof(DateTime));
      DataColumn cOrderAmount = 
      new DataColumn("OrderAmount", typeof(decimal));
      tOrders.Columns.Add(cOrderAmount);
      tOrders.Columns.Add(cID);
      tOrders.Columns.Add(cOrderDate);

      // Add the tables to the DataSet.
      myDataSet.Tables.Add(tCust);
      myDataSet.Tables.Add(tOrders);

      // Create a DataRelation, and add it to the DataSet.
      DataRelation dr = new DataRelation
      ("custToOrders", cCustID , cID);
      myDataSet.Relations.Add(dr);
   
      /* Populates the tables. For each customer and order, 
      creates two DataRow variables. */
      DataRow newRow1;
      DataRow newRow2;

      // Create three customers in the Customers Table.
      for(int i = 1; i < 4; i++)
      {
         newRow1 = tCust.NewRow();
         newRow1["custID"] = i;
         // Add the row to the Customers table.
         tCust.Rows.Add(newRow1);
      }
      // Give each customer a distinct name.
      tCust.Rows[0]["custName"] = "Customer1";
      tCust.Rows[1]["custName"] = "Customer2";
      tCust.Rows[2]["custName"] = "Customer3";

      // Give the Current column a value.
      tCust.Rows[0]["Current"] = true;
      tCust.Rows[1]["Current"] = true;
      tCust.Rows[2]["Current"] = false;

      // For each customer, create five rows in the Orders table.
      for(int i = 1; i < 4; i++)
      {
         for(int j = 1; j < 6; j++)
         {
            newRow2 = tOrders.NewRow();
            newRow2["CustID"]= i;
            newRow2["orderDate"]= new DateTime(2001, i, j * 2);
            newRow2["OrderAmount"] = i * 10 + j  * .1;
            // Add the row to the Orders table.
            tOrders.Rows.Add(newRow2);
         }
      }
   }
}


C++
#using <system.dll>
#using <system.data.dll>
#using <system.drawing.dll>
#using <system.windows.forms.dll>
#using <system.xml.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Windows::Forms;

#define null 0
public ref class Form1: public System::Windows::Forms::Form
{
private:
   System::ComponentModel::Container^ components;
   Button^ button1;
   Button^ button2;
   DataGrid^ myDataGrid;
   DataSet^ myDataSet;
   bool TablesAlreadyAdded;

public:
   Form1()
   {
      // Required for Windows Form Designer support.
      InitializeComponent();

      // Call SetUp to bind the controls.
      SetUp();
   }

public:
   ~Form1()
   {
      if ( components != nullptr )
      {
         delete components;
      }
   }

private:
   void InitializeComponent()
   {
      // Create the form and its controls.
      this->components = gcnew System::ComponentModel::Container;
      this->button1 = gcnew System::Windows::Forms::Button;
      this->button2 = gcnew System::Windows::Forms::Button;
      this->myDataGrid = gcnew DataGrid;
      this->Text = "DataGrid Control Sample";
      this->ClientSize = System::Drawing::Size( 450, 330 );
      button1->Location = System::Drawing::Point( 24, 16 );
      button1->Size = System::Drawing::Size( 120, 24 );
      button1->Text = "Change Appearance";
      button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click );
      button2->Location = System::Drawing::Point( 150, 16 );
      button2->Size = System::Drawing::Size( 120, 24 );
      button2->Text = "Get Binding Manager";
      button2->Click += gcnew System::EventHandler( this, &Form1::button2_Click );
      myDataGrid->Location = System::Drawing::Point( 24, 50 );
      myDataGrid->Size = System::Drawing::Size( 300, 200 );
      myDataGrid->CaptionText = "Microsoft DataGrid Control";
      myDataGrid->MouseUp += gcnew MouseEventHandler( this, &Form1::Grid_MouseUp );
      this->Controls->Add( button1 );
      this->Controls->Add( button2 );
      this->Controls->Add( myDataGrid );
   }

   void SetUp()
   {
      // Create a DataSet with two tables and one relation.
      MakeDataSet();

      /* Bind the DataGrid to the DataSet. The dataMember
        specifies that the Customers table should be displayed.*/
      myDataGrid->SetDataBinding( myDataSet, "Customers" );
   }

private:
   void button1_Click( Object^ sender, System::EventArgs^ e )
   {
      if ( TablesAlreadyAdded )
            return;

      AddCustomDataTableStyle();
   }

private:
   void AddCustomDataTableStyle()
   {
      DataGridTableStyle^ ts1 = gcnew DataGridTableStyle;
      ts1->MappingName = "Customers";

      // Set other properties.
      ts1->AlternatingBackColor = Color::LightGray;

      /* Add a GridColumnStyle and set its MappingName 
        to the name of a DataColumn in the DataTable. 
        Set the HeaderText and Width properties. */
      DataGridColumnStyle^ boolCol = gcnew DataGridBoolColumn;
      boolCol->MappingName = "Current";
      boolCol->HeaderText = "IsCurrent Customer";
      boolCol->Width = 150;
      ts1->GridColumnStyles->Add( boolCol );

      // Add a second column style.
      DataGridColumnStyle^ TextCol = gcnew DataGridTextBoxColumn;
      TextCol->MappingName = "custName";
      TextCol->HeaderText = "Customer Name";
      TextCol->Width = 250;
      ts1->GridColumnStyles->Add( TextCol );

      // Create the second table style with columns.
      DataGridTableStyle^ ts2 = gcnew DataGridTableStyle;
      ts2->MappingName = "Orders";

      // Set other properties.
      ts2->AlternatingBackColor = Color::LightBlue;

      // Create new ColumnStyle objects
      DataGridColumnStyle^ cOrderDate = gcnew DataGridTextBoxColumn;
      cOrderDate->MappingName = "OrderDate";
      cOrderDate->HeaderText = "Order Date";
      cOrderDate->Width = 100;
      ts2->GridColumnStyles->Add( cOrderDate );

      /* Use a PropertyDescriptor to create a formatted
        column. First get the PropertyDescriptorCollection
        for the data source and data member. */
      PropertyDescriptorCollection^ pcol = this->BindingContext[myDataSet, "Customers.custToOrders"]->GetItemProperties();

      /* Create a formatted column using a PropertyDescriptor.
        The formatting character "c" specifies a currency format. */
      DataGridColumnStyle^ csOrderAmount = gcnew DataGridTextBoxColumn( pcol[ "OrderAmount" ],"c",true );
      csOrderAmount->MappingName = "OrderAmount";
      csOrderAmount->HeaderText = "Total";
      csOrderAmount->Width = 100;
      ts2->GridColumnStyles->Add( csOrderAmount );

      /* Add the DataGridTableStyle instances to 
        the GridTableStylesCollection. */
      myDataGrid->TableStyles->Add( ts1 );
      myDataGrid->TableStyles->Add( ts2 );

      // Sets the TablesAlreadyAdded to true so this doesn't happen again.
      TablesAlreadyAdded = true;
   }

private:
   void button2_Click( Object^ sender, System::EventArgs^ e )
   {
      BindingManagerBase^ bmGrid;
      bmGrid = BindingContext[myDataSet, "Customers"];
      MessageBox::Show( String::Concat( "Current BindingManager Position: ", bmGrid->Position )->ToString() );
   }

private:
   void Grid_MouseUp( Object^ sender, MouseEventArgs^ e )
   {
      // Create a HitTestInfo object using the HitTest method.
      // Get the DataGrid by casting sender.
      DataGrid^ myGrid = dynamic_cast<DataGrid^>(sender);
      DataGrid::HitTestInfo ^ myHitInfo = myGrid->HitTest( e->X, e->Y );
      Console::WriteLine( myHitInfo );
      Console::WriteLine( myHitInfo->Type );
      Console::WriteLine( myHitInfo->Row );
      Console::WriteLine( myHitInfo->Column );
   }

   // Create a DataSet with two tables and populate it.
   void MakeDataSet()
   {
      // Create a DataSet.
      myDataSet = gcnew DataSet( "myDataSet" );

      // Create two DataTables.
      DataTable^ tCust = gcnew DataTable( "Customers" );
      DataTable^ tOrders = gcnew DataTable( "Orders" );

      // Create two columns, and add them to the first table.
      DataColumn^ cCustID = gcnew DataColumn( "CustID",__int32::typeid );
      DataColumn^ cCustName = gcnew DataColumn( "CustName" );
      DataColumn^ cCurrent = gcnew DataColumn( "Current",bool::typeid );
      tCust->Columns->Add( cCustID );
      tCust->Columns->Add( cCustName );
      tCust->Columns->Add( cCurrent );

      // Create three columns, and add them to the second table.
      DataColumn^ cID = gcnew DataColumn( "CustID",__int32::typeid );
      DataColumn^ cOrderDate = gcnew DataColumn( "orderDate",DateTime::typeid );
      DataColumn^ cOrderAmount = gcnew DataColumn( "OrderAmount",Decimal::typeid );
      tOrders->Columns->Add( cOrderAmount );
      tOrders->Columns->Add( cID );
      tOrders->Columns->Add( cOrderDate );

      // Add the tables to the DataSet.
      myDataSet->Tables->Add( tCust );
      myDataSet->Tables->Add( tOrders );

      // Create a DataRelation, and add it to the DataSet.
      DataRelation^ dr = gcnew DataRelation( "custToOrders",cCustID,cID );
      myDataSet->Relations->Add( dr );

      /* Populate the tables. For each customer and order, 
        create need two DataRow variables. */
      DataRow^ newRow1;
      DataRow^ newRow2;

      // Create three customers in the Customers Table.
      for ( int i = 1; i < 4; i++ )
      {
         newRow1 = tCust->NewRow();
         newRow1[ "custID" ] = i;
         
         // Add the row to the Customers table.
         tCust->Rows->Add( newRow1 );
      }
      tCust->Rows[ 0 ][ "custName" ] = "Customer1";
      tCust->Rows[ 1 ][ "custName" ] = "Customer2";
      tCust->Rows[ 2 ][ "custName" ] = "Customer3";

      // Give the Current column a value.
      tCust->Rows[ 0 ][ "Current" ] = true;
      tCust->Rows[ 1 ][ "Current" ] = true;
      tCust->Rows[ 2 ][ "Current" ] = false;

      // For each customer, create five rows in the Orders table.
      for ( int i = 1; i < 4; i++ )
      {
         for ( int j = 1; j < 6; j++ )
         {
            newRow2 = tOrders->NewRow();
            newRow2[ "CustID" ] = i;
            newRow2[ "orderDate" ] = DateTime(2001,i,j * 2);
            newRow2[ "OrderAmount" ] = i * 10 + j * .1;
            
            // Add the row to the Orders table.
            tOrders->Rows->Add( newRow2 );
         }
      }
   }
};

int main()
{
   Application::Run( gcnew Form1 );
}


J#
import System.*;
import System.ComponentModel.*;
import System.Data.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class Form1 extends System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    private Button button1;
    private Button button2;
    private DataGrid myDataGrid;
    private DataSet myDataSet;
    private boolean tablesAlreadyAdded;

    public Form1()
    {
        // Required for Windows Form Designer support.
        InitializeComponent();
        // Call SetUp to bind the controls.
        SetUp();
    } //Form1


    protected void Dispose(boolean disposing)
    {
        if (disposing) {
            if (components != null) {
                components.Dispose();
            }
        }
        super.Dispose(disposing);
    } //Dispose

    private void InitializeComponent()
    {
        // Create the form and its controls.
        this.components = new System.ComponentModel.Container();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.myDataGrid = new DataGrid();
        this.set_Text("DataGrid Control Sample");
        this.set_ClientSize(new System.Drawing.Size(450, 330));
        button1.set_Location(new Point(24, 16));
        button1.set_Size(new System.Drawing.Size(120, 24));
        button1.set_Text("Change Appearance");
        button1.add_Click(new System.EventHandler(button1_Click));
        button2.set_Location(new Point(150, 16));
        button2.set_Size(new System.Drawing.Size(120, 24));
        button2.set_Text("Get Binding Manager");
        button2.add_Click(new System.EventHandler(button2_Click));
        myDataGrid.set_Location(new Point(24, 50));
        myDataGrid.set_Size(new Size(300, 200));
        myDataGrid.set_CaptionText("Microsoft DataGrid Control");
        myDataGrid.add_MouseUp(new MouseEventHandler(Grid_MouseUp));
        this.get_Controls().Add(button1);
        this.get_Controls().Add(button2);
        this.get_Controls().Add(myDataGrid);
    } //InitializeComponent

    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    private void SetUp()
    {
        // Create a DataSet with two tables and one relation.
        MakeDataSet();

        /*    Bind the DataGrid to the DataSet. The dataMember
            specifies that the Customers table should be displayed.
         */
        myDataGrid.SetDataBinding(myDataSet, "Customers");
    } //SetUp

    protected void button1_Click(Object sender, System.EventArgs e)
    {
        if (tablesAlreadyAdded) {
            return ;
        }
        AddCustomDataTableStyle();
    } //button1_Click

    private void AddCustomDataTableStyle()
    {
        DataGridTableStyle ts1 = new DataGridTableStyle();
        ts1.set_MappingName("Customers");

        // Set other properties.
        ts1.set_AlternatingBackColor(Color.get_LightGray());

        /*  Add a GridColumnStyle and set its MappingName
            to the name of a DataColumn in the DataTable. 
            Set the HeaderText and Width properties. 
         */
        DataGridColumnStyle boolCol = new DataGridBoolColumn();
        boolCol.set_MappingName("Current");
        boolCol.set_HeaderText("IsCurrent Customer");
        boolCol.set_Width(150);
        ts1.get_GridColumnStyles().Add(boolCol);

        // Add a second column style.
        DataGridColumnStyle textCol = new DataGridTextBoxColumn();
        textCol.set_MappingName("custName");
        textCol.set_HeaderText("Customer Name");
        textCol.set_Width(250);
        ts1.get_GridColumnStyles().Add(textCol);

        // Create the second table style with columns.
        DataGridTableStyle ts2 = new DataGridTableStyle();
        ts2.set_MappingName("Orders");

        // Set other properties.
        ts2.set_AlternatingBackColor(Color.get_LightBlue());

        // Create new ColumnStyle objects
        DataGridColumnStyle cOrderDate = new DataGridTextBoxColumn();
        cOrderDate.set_MappingName("OrderDate");
        cOrderDate.set_HeaderText("Order Date");
        cOrderDate.set_Width(100);
        ts2.get_GridColumnStyles().Add(cOrderDate);

        /*   Use a PropertyDescriptor to create a formatted
             column. First get the PropertyDescriptorCollection
             for the data source and data member. 
         */
        PropertyDescriptorCollection pcol =
            this.get_BindingContext().get_Item(myDataSet, 
                "Customers.custToOrders").GetItemProperties();

        /*  Create a formatted column using a PropertyDescriptor.
            The formatting character "c" specifies a currency format. 
         */
        DataGridColumnStyle csOrderAmount = 
            new DataGridTextBoxColumn(pcol.get_Item("OrderAmount"), 
            "c", true);
        csOrderAmount.set_MappingName("OrderAmount");
        csOrderAmount.set_HeaderText("Total");
        csOrderAmount.set_Width(100);
        ts2.get_GridColumnStyles().Add(csOrderAmount);

        /*  Add the DataGridTableStyle instances to 
            the GridTableStylesCollection. 
         */
        myDataGrid.get_TableStyles().Add(ts1);
        myDataGrid.get_TableStyles().Add(ts2);

        // Sets the tablesAlreadyAdded to true so this doesn't happen again.
        tablesAlreadyAdded = true;
    } //AddCustomDataTableStyle

    protected void button2_Click(Object sender, System.EventArgs e)
    {
        BindingManagerBase bmGrid;
        bmGrid = get_BindingContext().get_Item(myDataSet, "Customers");
        MessageBox.Show(("Current BindingManager Position: "
            + bmGrid.get_Position()));
    } //button2_Click

    private void Grid_MouseUp(Object sender, MouseEventArgs e)
    {
        // Create a HitTestInfo object using the HitTest method.
        // Get the DataGrid by casting sender.
        DataGrid myGrid = ((DataGrid)(sender));
        DataGrid.HitTestInfo myHitInfo = myGrid.HitTest(e.get_X(), e.get_Y());

        Console.WriteLine(myHitInfo);
        Console.WriteLine(myHitInfo.get_Type());
        Console.WriteLine(myHitInfo.get_Row());
        Console.WriteLine(myHitInfo.get_Column());
    } //Grid_MouseUp

    // Create a DataSet with two tables and populate it.
    private void MakeDataSet()
    {
        // Create a DataSet.
        myDataSet = new DataSet("myDataSet");

        // Create two DataTables.
        DataTable tCust = new DataTable("Customers");
        DataTable tOrders = new DataTable("Orders");

        // Create two columns, and add them to the first table.
        DataColumn cCustID = new DataColumn("CustID", int.class.ToType());
        DataColumn cCustName = new DataColumn("CustName");
        DataColumn cCurrent = new DataColumn("Current",boolean.class.ToType());

        tCust.get_Columns().Add(cCustID);
        tCust.get_Columns().Add(cCustName);
        tCust.get_Columns().Add(cCurrent);

        // Create three columns, and add them to the second table.
        DataColumn cID = new DataColumn("CustID", int.class.ToType());
        DataColumn cOrderDate = new DataColumn(    "orderDate", 
            DateTime.class.ToType());
        DataColumn cOrderAmount = new DataColumn("OrderAmount", 
            System.Decimal.class.ToType());
        tOrders.get_Columns().Add(cOrderAmount);
        tOrders.get_Columns().Add(cID);
        tOrders.get_Columns().Add(cOrderDate);

        // Add the tables to the DataSet.
        myDataSet.get_Tables().Add(tCust);
        myDataSet.get_Tables().Add(tOrders);

        // Create a DataRelation, and add it to the DataSet.
        DataRelation dr = new DataRelation("custToOrders", cCustID, cID);
        myDataSet.get_Relations().Add(dr);

        /*  Populates the tables. For each customer and order, 
            creates two DataRow variables. 
         */
        DataRow newRow1;
        DataRow newRow2;

        // Create three customers in the Customers Table.
        for (int i = 1; i < 4; i++) {
            newRow1 = tCust.NewRow();
            newRow1.set_Item("custID", (System.Int32)i);

            // Add the row to the Customers table.
            tCust.get_Rows().Add(newRow1);
        }

        // Give each customer a distinct name.
        tCust.get_Rows().get_Item(0).set_Item("custName", "Customer1");
        tCust.get_Rows().get_Item(1).set_Item("custName", "Customer2");
        tCust.get_Rows().get_Item(2).set_Item("custName", "Customer3");

        // Give the Current column a value.
        tCust.get_Rows().get_Item(0).set_Item("Current", (System.Boolean)true);
        tCust.get_Rows().get_Item(1).set_Item("Current", (System.Boolean)true);
        tCust.get_Rows().get_Item(2).set_Item("Current",(System.Boolean)false);

        // For each customer, create five rows in the Orders table.
        for (int i = 1; i < 4; i++) {
            for (int j = 1; j < 6; j++) {
                newRow2 = tOrders.NewRow();
                newRow2.set_Item("CustID", (System.Int32)i);
                newRow2.set_Item("orderDate", new DateTime(2001, i, j * 2));
                newRow2.set_Item("OrderAmount", 
                    (System.Single)(i * 10 + j * 0.1));

                // Add the row to the Orders table.
                tOrders.get_Rows().Add(newRow2);
            }
        }
    } //MakeDataSet
} //Form1
Hiérarchie d'héritageHiérarchie d'héritage
System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
        System.Windows.Forms.DataGrid
Sécurité des threadsSécurité des threads
Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Plates-formesPlates-formes

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

Informations de versionInformations de version

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0
Voir aussiVoir aussi

Ces informations proviennent du site de http://msdn2.microsoft.com
Source de cette page : http://msdn2.microsoft.com/fr-fr/library/system.windows.forms.datagrid.aspx

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

16 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-4294
Document créé le 06/10/06 23:34, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-system.windows.forms.datagrid.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,32 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Le génie commence les beaux ouvrages, mais le travail seul les achève.

Joseph Joubert
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 04:58, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)