DataGrid-Klasse

Zeigt ADO.NET-Daten in einem bildlauffähigen Datenblatt an. Obwohl das DataGrid-Steuerelement durch das DataGridView-Steuerelement ersetzt und funktionell erweitert wird, wird das DataGrid-Steuerelement sowohl aus Gründen der Abwärtskompatibilität als auch, falls gewünscht, für die zukünftige Verwendung beibehalten.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

Syntax

'Declaration
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
<ComVisibleAttribute(True)> _
Public Class DataGrid
    Inherits Control
    Implements ISupportInitialize, IDataGridEditingService
'Usage
Dim instance As DataGrid
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
[ComVisibleAttribute(true)] 
public class DataGrid : Control, ISupportInitialize, IDataGridEditingService
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] 
[ComVisibleAttribute(true)] 
public ref class DataGrid : public Control, ISupportInitialize, IDataGridEditingService
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
/** @attribute ComVisibleAttribute(true) */ 
public class DataGrid extends Control implements ISupportInitialize, IDataGridEditingService
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
ComVisibleAttribute(true) 
public class DataGrid extends Control implements ISupportInitialize, IDataGridEditingService

Hinweise

Das System.Windows.Forms.DataGrid zeigt Verknüpfungen im Webformat zu untergeordneten Tabellen an. Durch Klicken auf einen Hyperlink wechseln Sie zur untergeordneten Tabelle. Wenn eine untergeordnete Tabelle geöffnet wird, dann wird in der Beschriftung eine Schaltfläche Zurück angezeigt, mit der Sie zurück zur übergeordneten Tabelle navigieren können. Die Daten aus den Zeilen der übergeordneten Tabelle werden unterhalb der Beschriftung und oberhalb der Spaltenköpfe angezeigt. Sie können die Daten der Zeilen der übergeordneten Tabelle ausblenden, indem Sie auf die Schaltfläche rechts von der Schaltfläche Zurück klicken.

Zum Anzeigen einer Tabelle im System.Windows.Forms.DataGrid zur Laufzeit verwenden Sie die SetDataBinding-Methode, um die DataSource-Eigenschaft und die DataMember-Eigenschaft auf eine gültige Datenquelle festzulegen. Folgende Datenquellen sind gültig:

Weitere Informationen über die DataSet-Klasse finden Sie unter Verwenden von DataSets in ADO.NET.

Sie können ein Datenblatt erstellen, in dem Daten bearbeitet, aber keine neuen Zeilen hinzufügt werden können, indem Sie eine DataView als Datenquelle verwenden und die AllowNew-Eigenschaft auf false festlegen.

Datenquellen werden darüber hinaus von BindingManagerBase-Objekten verwaltet. Für jede Tabelle in einer Datenquelle kann eine BindingManagerBase aus dem BindingContext des Formulars zurückgegeben werden. Sie können z. B. die Anzahl der Zeilen in einer Datenquelle bestimmen, indem Sie die Count-Eigenschaft des zugeordneten BindingManagerBase-Objekts zurückgeben.

Zum Überprüfen von Daten verwenden Sie die zugrunde liegenden Objekte, die Daten und deren Ereignisse darstellen. Wenn die Daten z. B. aus einer DataTable in einem DataSet stammen, verwenden Sie das ColumnChanging-Ereignis und das RowChanging-Ereignis.

Hinweis

Da die Anzahl der Spalten durch Hinzufügen oder Löschen von Membern der GridColumnStylesCollection angepasst und die Zeilen nach Spalten sortiert werden können, ist nicht sichergestellt, dass die Werte der RowNumber-Eigenschaft und der ColumnNumber-Eigenschaft dem DataRow-Index und dem DataColumn-Index in einer DataTable entsprechen. Daher sollten Sie es vermeiden, diese Eigenschaften im Validating-Ereignis für die Datenvalidierung zu verwenden.

Um die gegenwärtig ausgewählte Zelle zu bestimmen, verwenden Sie die CurrentCell-Eigenschaft. Mit der Item-Eigenschaft, die entweder den Zeilen- und Spaltenindex der Zelle oder eine einzelne DataGridCell akzeptiert, können Sie den Wert einer beliebigen Zelle ändern. Überwachen Sie das CurrentCellChanged-Ereignis, um festzustellen, wann der Benutzer eine andere Zelle auswählt.

Mit der HitTest-Methode im MouseDown-Ereignis können Sie bestimmen, auf welchen Bereich des Steuerelements der Benutzer geklickt hat. Die HitTest-Methode gibt ein DataGrid.HitTestInfo-Objekt zurück, das die Zeile und die Spalte des Bereichs enthält, auf den geklickt wurde.

Für die Steuerung der Darstellung des Steuerelements zur Laufzeit stehen verschiedene Eigenschaften zum Festlegen der Farb- und Beschriftungsattribute zur Verfügung, z. B. CaptionForeColor, CaptionBackColor, CaptionFont usw.

Die Darstellung des angezeigten Datenblatts oder der angezeigten Datenblätter kann darüber hinaus durch Erstellen von DataGridTableStyle-Objekten verändert werden, die der GridTableStylesCollection hinzugefügt werden, auf die über die TableStyles-Eigenschaft zugegriffen wird. Wenn die DataSource z. B. auf ein DataSet mit drei DataTable-Objekten festgelegt ist, können Sie der Auflistung drei DataGridTableStyle-Objekte hinzufügen, für jede Tabelle eines. Zum Synchronisieren der einzelnen DataGridTableStyle-Objekte mit einer DataTable legen Sie den MappingName des DataGridTableStyle auf den TableName der DataTable fest. Weitere Informationen über das Binden an ein Array von Objekten finden Sie unter der DataGridTableStyle.MappingName-Eigenschaft.

Zum Erstellen einer benutzerdefinierten Tabellenansicht können Sie eine Instanz einer DataGridTextBoxColumn-Klasse oder DataGridBoolColumn-Klasse erstellen und das Objekt der GridTableStylesCollection hinzufügen, auf die über die TableStyles-Eigenschaft zugegriffen wird. Beide Klassen erben vom DataGridColumnStyle. Legen Sie für jedes Spaltenformat den MappingName auf den ColumnName der Spalte fest, die im Datenblatt angezeigt werden soll. Zum Ausblenden einer Spalte legen Sie dessen MappingName auf einen Wert fest, der kein gültiger ColumnName ist.

Legen Sie zum Formatieren des Texts in einer Spalte die Format-Eigenschaft der DataGridTextBoxColumn auf einen der Werte aus Formatzeichenfolgen für Datum und Uhrzeit oder Standardmäßige Zahlenformatzeichenfolgen fest.

Das DataGrid kann nur an ein stark typisiertes Array von Objekten gebunden werden, wenn der Objekttyp öffentliche Eigenschaften enthält. Legen Sie zum Erstellen eines DataGridTableStyle, der das Array anzeigt, die DataGridTableStyle.MappingName-Eigenschaft auf typename[] fest, wobei typename durch den Namen des Objekttyps ersetzt wird. Bei der MappingName-Eigenschaft wird die Groß- und Kleinschreibung berücksichtigt, achten Sie daher darauf, dass der Typname exakt überstimmt. Ein Beispiel finden Sie unter der MappingName-Eigenschaft.

Sie können das DataGrid auch an eine ArrayList binden. Ein Feature der ArrayList ist, dass sie Objekte verschiedenen Typs enthalten kann. Das DataGrid kann aber nur an eine Liste gebunden werden, in der alle Elemente von demselben Typ wie das erste Element sind. Das heißt, dass alle Objekte denselben Typ haben oder von derselben Klasse erben müssen wie das erste Listenelement. Wenn z. B. das erste Element in der Liste ein Control ist, kann das zweite Element eine TextBox sein (die von Control erbt). Wenn jedoch das erste Element eine TextBox ist, kann das zweite Objekt kein Control sein. Eine ArrayList muss außerdem Elemente enthalten, wenn es gebunden wird. Eine leere ArrayList ergibt ein leeres Datenblatt. Darüber hinaus müssen die Objekte in der ArrayList öffentliche Eigenschaften enthalten. Legen Sie zum Binden an eine ArrayList den MappingName des DataGridTableStyle auf "ArrayList" (den Typnamen) fest.

Sie können für jeden DataGridTableStyle Farb- und Beschriftungsattribute festlegen, die die Einstellungen für das System.Windows.Forms.DataGrid-Steuerelement überschreiben. Wenn diese Eigenschaften allerdings nicht festgelegt werden, werden als Standardeinstellungen die Einstellungen für das Steuerelement verwendet. Die folgenden Eigenschaften können mit DataGridTableStyle-Eigenschaften überschrieben werden:

Sie können die Darstellung einzelner Spalten anpassen, indem Sie der GridColumnStylesCollection, auf die über die GridColumnStyles-Eigenschaft jedes DataGridTableStyle zugegriffen wird, DataGridColumnStyle-Objekte hinzufügen. Zum Synchronisieren jedes DataGridColumnStyle mit einer DataColumn in der DataTable legen Sie den MappingName auf den ColumnName einer DataColumn fest. Beim Erstellen eines DataGridColumnStyle können Sie außerdem eine Formatzeichenfolge festlegen, die die Darstellung von Daten in der Spalte angibt. Beispielsweise können Sie angeben, dass die Spalte für die Anzeige von in der Tabelle enthaltenen Datumsangaben ein kurzes Datumsformat verwendet.

Warnung

Erstellen Sie vor dem Hinzufügen von DataGridTableStyle-Objekten zur GridTableStylesCollection immer DataGridColumnStyle-Objekte, und fügen Sie diese der GridColumnStylesCollection hinzu. Wenn Sie der Auflistung einen leeren DataGridTableStyle mit einem gültigen MappingName-Wert hinzufügen, werden automatisch DataGridColumnStyle-Objekte generiert. Folglich wird beim Versuch, der GridColumnStylesCollection neue DataGridColumnStyle-Objekte mit doppelten MappingName-Werten hinzuzufügen, eine Ausnahme ausgelöst.

Hinweis

Obwohl das DataGrid-Steuerelement durch das DataGridView-Steuerelement ersetzt und funktionell erweitert wird, wird das DataGrid-Steuerelement sowohl aus Gründen der Abwärtskompatibilität als auch, falls gewünscht, für die zukünftige Verwendung beibehalten. Weitere Informationen finden Sie unter Unterschiede zwischen dem DataGridView-Steuerelement und dem DataGrid-Steuerelement in Windows Forms.

Beispiel

Im folgenden Codebeispiel werden ein Windows Form, ein DataSet mit zwei DataTable-Objekten sowie eine DataRelation, die zwei Tabellen verknüpft, erstellt. Für die Anzeige der Daten wird anschließend unter Verwendung der SetDataBinding-Methode ein System.Windows.Forms.DataGrid-Steuerelement an ein DataSet gebunden. Eine Schaltfläche im Formular ändert die Darstellung des Datenblatts, indem zwei DataGridTableStyle-Objekte erstellt werden und der MappingName jedes Objekts auf einen TableName eines der DataTable-Objekte festgelegt wird. Das Beispiel enthält außerdem Code im MouseUp-Ereignis, das die HitTest-Methode verwendet, um die Spalte, die Zeile und den Bereich des Datenblatts auszugeben, auf den geklickt wurde.

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 
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);
         }
      }
   }
}
#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 );
}
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

Vererbungshierarchie

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
        System.Windows.Forms.DataGrid

Threadsicherheit

Alle öffentlichen statischen (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.

Plattformen

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

DataGrid-Member
System.Windows.Forms-Namespace
DataSet
DataView
DataTable
DataRow

Weitere Ressourcen

ADO.NET