DataGrid 类

在可滚动的网格中显示 ADO .NET 数据。DataGridView 控件对 DataGrid 控件的功能进行了替换和添加,但是考虑到向后兼容性和将来的使用(如果您选择),仍然保留了 DataGrid 控件。

**命名空间:**System.Windows.Forms
**程序集:**System.Windows.Forms(在 system.windows.forms.dll 中)

语法

声明
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
<ComVisibleAttribute(True)> _
Public Class DataGrid
    Inherits Control
    Implements ISupportInitialize, IDataGridEditingService
用法
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

备注

System.Windows.Forms.DataGrid 显示指向子表的类似 Web 的链接。您可以单击链接定位到子表。在显示子表时,标题中显示后退按钮,可以单击它向后定位到父表。父行的数据显示在标题下面、列标头的上面。可以通过单击后退按钮右边的按钮来隐藏父行信息。

若要在运行时在 System.Windows.Forms.DataGrid 中显示表,请使用 SetDataBinding 方法将 DataSourceDataMember 属性设置为有效的数据源。下列数据源有效:

有关 DataSet 类的更多信息,请参见 在 ADO.NET 中使用 DataSet

通过将 DataView 用作数据源并将 AllowNew 属性设置为 false,可以创建网格,该网格允许用户编辑数据但禁止他们添加新行。

数据源可通过 BindingManagerBase 对象进一步进行管理。对于数据源中的每个表,均可从窗体的 BindingContext 中返回一个 BindingManagerBase。例如,可通过返回关联的 BindingManagerBase 对象的 Count 属性来确定数据源所包含的行数。

若要验证数据,请使用代表数据及其事件的基础对象。例如,如果数据来自 DataSet 中的 DataTable,则可使用 ColumnChangingRowChanging 事件。

提示

由于可以自定义列数(通过添加或删除 GridColumnStylesCollection 的成员),而且可以按列对行进行排序,因此不能确保 RowNumberColumnNumber 属性值与 DataTable 中的 DataRowDataColumn 索引相符。因此,请避免在 Validating 事件中使用这些属性来验证数据。

若要确定所选择的单元格,请使用 CurrentCell 属性。可使用 Item 属性更改任意单元格的值,该属性可采用单元格的行索引和列索引或单个 DataGridCell。监视 CurrentCellChanged 事件以检测用户选择另一个单元格的时间。

若要确定用户所单击的控件的部分,请使用 MouseDown 事件中的 HitTest 方法。HitTest 方法返回一个 DataGrid.HitTestInfo 对象,该对象包含被单击区域的行和列。

若要在运行时管理控件的外观,有多个可用于设置颜色和标题属性的属性,包括 CaptionForeColorCaptionBackColorCaptionFont 等等。

可进一步修改所显示网格的外观,方法是创建 DataGridTableStyle 对象,并将它们添加到 GridTableStylesCollection 中,可通过 TableStyles 属性访问后者。例如,如果 DataSource 设置为包含三个 DataTable 对象的 DataSet,则可以向该集合添加三个 DataGridTableStyle 对象,每个表一个。若要将每个 DataGridTableStyle 对象与一个 DataTable 同步,请将 DataGridTableStyleMappingName 设置为 DataTableTableName。有关绑定到对象数组的更多信息,请参见 DataGridTableStyle.MappingName 属性。

要创建表的自定义视图,请创建 DataGridTextBoxColumnDataGridBoolColumn 类的一个实例,并将该对象添加到通过 TableStyles 属性访问的 GridTableStylesCollection 中。两个类都从 DataGridColumnStyle 继承。对于各列的样式,请将 MappingName 设置成要在网格中显示的列的 ColumnName。若要隐藏某列,请将其 MappingName 设置为除有效 ColumnName 之外的内容。

要设置列的文本格式,请将 DataGridTextBoxColumnFormat 属性设置成 日期与时间格式字符串标准数字格式字符串 中的某个值。

若要将 DataGrid 绑定到对象的强类型数组,该对象类型必须包含公共属性。若要创建一个显示此数组的 DataGridTableStyle,请将 DataGridTableStyle.MappingName 属性设置为 typename[],其中 typename 由该对象类型的名称替换。另外请注意,MappingName 属性区分大小写;类型名称必须完全匹配。有关示例,请参见 MappingName 属性。

也可以将 DataGrid 绑定到 ArrayListArrayList 的一个功能是它可以包含多种类型的对象,但当列表中的所有项与第一项具有相同的类型时,DataGrid 只能绑定到这类列表。这意味着所有的对象必须是同一种类型,或者必须从与列表中第一项相同的类继承。例如,如果列表中的第一项为 Control,则第二项可能为 TextBox(它从 Control 继承)。另一方面,如果第一项为 TextBox,则第二个对象就不可能是 Control。此外,ArrayList 在绑定时必须包含项目。空 ArrayList 会导致空网格。此外,ArrayList 中的对象必须包含公共属性。当绑定到 ArrayList 时,请将 DataGridTableStyleMappingName 设置为“ArrayList”(类型名)。

对于每个 DataGridTableStyle,都可以设置颜色和标题属性来重写 System.Windows.Forms.DataGrid 控件的设置。但是,如果未设置上述属性,则默认情况下使用控件的设置。可以通过 DataGridTableStyle 属性重写下列属性:

若要自定义单个列的外观,请将 DataGridColumnStyle 对象添加到 GridColumnStylesCollection 中,后者可以通过每个 DataGridTableStyleGridColumnStyles 属性来访问。若要使每个 DataGridColumnStyleDataTable 中的一个 DataColumn 同步,请将 MappingName 设置为某 DataColumnColumnName。在构造 DataGridColumnStyle 时,还可以设置指定列显示数据的方式的格式化字符串。例如,可以指定列使用短日期格式显示表中所包含的日期。

警告

在向 GridTableStylesCollection 添加 DataGridTableStyle 对象之前,始终应先创建 DataGridColumnStyle 对象并将其添加到 GridColumnStylesCollection。当向集合添加具有有效的 MappingName 值的空 DataGridTableStyle 时,将自动生成 DataGridColumnStyle 对象。因此,如果试图向 GridColumnStylesCollection 添加带有重复 MappingName 值的 DataGridColumnStyle 新对象时,将引发异常。

提示

DataGridView 控件对 DataGrid 控件的功能进行了替换和添加,但是考虑到向后兼容性和将来的使用,仍然保留了 DataGrid 控件(如果您选择)。有关更多信息,请参见 Windows 窗体 DataGridView 控件和 DataGrid 控件之间的区别

示例

下面的代码示例创建一个 Windows 窗体、包含两个 DataTable 对象的一个 DataSet 和关联这两个表的一个 DataRelation。若要显示数据,请随后通过 SetDataBinding 方法将一个 System.Windows.Forms.DataGrid 控件绑定到 DataSet。通过创建两个 DataGridTableStyle 对象并将每个对象的 MappingName 设置为 DataTable 对象之一的 TableName,窗体上的某按钮可更改网格的外观。该示例还在 MouseUp 事件中包含代码,使用 HitTest 方法来输出所单击的行、列和网格的部分。

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

继承层次结构

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

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

DataGrid 成员
System.Windows.Forms 命名空间
DataSet
DataView
DataTable
DataRow

其他资源

ADO.NET