DataGridView.DataSource DataGridView.DataSource DataGridView.DataSource DataGridView.DataSource Property


DataGridView でデータが表示される対象のデータ ソースを取得または設定します。Gets or sets the data source that the DataGridView is displaying data for.

 property System::Object ^ DataSource { System::Object ^ get(); void set(System::Object ^ value); };
public object DataSource { get; set; }
member this.DataSource : obj with get, set
Public Property DataSource As Object


表示される DataGridView のデータを格納しているオブジェクト。The object that contains data for the DataGridView to display.


データ ソースでエラーが発生しました。DataError イベントのハンドラーがないか、ハンドラーが ThrowException プロパティを true に設定しました。An error occurred in the data source and either there is no handler for the DataError event or the handler has set the ThrowException property to true. 通常、例外オブジェクトは型 FormatException にキャストできます。The exception object can typically be cast to type FormatException.

次のコード例は、単純なデータ バインドを初期化する方法を示しますDataGridViewします。The following code example demonstrates how to initialize a simple data-bound DataGridView. 設定する方法も示します、DataSourceプロパティ。It also demonstrates how to set the DataSource property.

#using <System.Transactions.dll>
#using <System.EnterpriseServices.dll>
#using <System.Xml.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;
using namespace System::Drawing;
public ref class Form1: public System::Windows::Forms::Form
      : Form()
      //This call is required by the Windows Form Designer.
      //Add any initialization after the InitializeComponent() call


      if ( components != nullptr )
         delete components;

   System::Windows::Forms::DataGridView ^ dataGridView1;
   System::Windows::Forms::BindingSource ^ bindingSource1;

   //Required by the Windows Form Designer
   System::ComponentModel::IContainer^ components;

   //NOTE: The following procedure is required by the Windows Form Designer
   //It can be modified using the Windows Form Designer.  
   //Do not modify it using the code editor.

   void InitializeComponent()
      this->dataGridView1 = gcnew System::Windows::Forms::DataGridView;
      this->bindingSource1 = gcnew System::Windows::Forms::BindingSource;

      this->dataGridView1->Location = System::Drawing::Point( 96, 71 );
      this->dataGridView1->Name = "DataGridView1";
      this->dataGridView1->Size = System::Drawing::Size( 321, 286 );
      this->dataGridView1->TabIndex = 0;

      this->ClientSize = System::Drawing::Size( 518, 413 );
      this->Controls->Add( this->dataGridView1 );
      this->Name = "Form1";
      this->Text = "Form1";
      this->ResumeLayout( false );


   static property Form1^ GetInstance 
      Form1^ get()
         if ( m_DefaultInstance == nullptr || m_DefaultInstance->IsDisposed )
            System::Threading::Monitor::Enter( m_SyncObject );
               if ( m_DefaultInstance == nullptr || m_DefaultInstance->IsDisposed )
                  m_DefaultInstance = gcnew Form1;
               System::Threading::Monitor::Exit( m_SyncObject );

         return m_DefaultInstance;

   static Form1^ m_DefaultInstance;
   static Object^ m_SyncObject = gcnew Object;

   void InitializeDataGridView()
         // Set up the DataGridView.
         dataGridView1->Dock = DockStyle::Fill;

         // Automatically generate the DataGridView columns.
         dataGridView1->AutoGenerateColumns = true;

         // Set up the data source.
         bindingSource1->DataSource = GetData( "Select * From Products" );
         dataGridView1->DataSource = bindingSource1;

         // Automatically resize the visible rows.
         dataGridView1->AutoSizeRowsMode = DataGridViewAutoSizeRowsMode::DisplayedCellsExceptHeaders;

         // Set the DataGridView control's border.
         dataGridView1->BorderStyle = BorderStyle::Fixed3D;

         // Put the cells in edit mode when user enters them.
         dataGridView1->EditMode = DataGridViewEditMode::EditOnEnter;
      catch ( SqlException^ ) 
         MessageBox::Show( "To run this sample replace connection.ConnectionString"
         " with a valid connection string to a Northwind"
         " database accessible to your system.", "ERROR", MessageBoxButtons::OK, MessageBoxIcon::Exclamation );
      catch ( System::Exception^ ex ) 
         MessageBox::Show( ex->ToString() );

   DataTable^ GetData( String^ sqlCommand )
      String^ connectionString = "Integrated Security=SSPI;Persist Security Info=False;"
      "Initial Catalog=Northwind;Data Source= localhost";
      SqlConnection^ northwindConnection = gcnew SqlConnection( connectionString );
      SqlCommand^ command = gcnew SqlCommand( sqlCommand,northwindConnection );
      SqlDataAdapter^ adapter = gcnew SqlDataAdapter;
      adapter->SelectCommand = command;
      DataTable^ table = gcnew DataTable;
      adapter->Fill( table );
      return table;

int main()
   Application::Run( gcnew Form1 );
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Drawing;

public class Form1 : System.Windows.Forms.Form
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bindingSource1 = new BindingSource();

    public Form1()
        dataGridView1.Dock = DockStyle.Fill;

    private void InitializeDataGridView()
            // Set up the DataGridView.
            dataGridView1.Dock = DockStyle.Fill;

            // Automatically generate the DataGridView columns.
            dataGridView1.AutoGenerateColumns = true;

            // Set up the data source.
            bindingSource1.DataSource = GetData("Select * From Products");
            dataGridView1.DataSource = bindingSource1;

            // Automatically resize the visible rows.
            dataGridView1.AutoSizeRowsMode =

            // Set the DataGridView control's border.
            dataGridView1.BorderStyle = BorderStyle.Fixed3D;

            // Put the cells in edit mode when user enters them.
            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
        catch (SqlException)
            MessageBox.Show("To run this sample replace connection.ConnectionString" +
                " with a valid connection string to a Northwind" +
                " database accessible to your system.", "ERROR",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

    private static DataTable GetData(string sqlCommand)
        string connectionString = "Integrated Security=SSPI;" +
            "Persist Security Info=False;" +
            "Initial Catalog=Northwind;Data Source=localhost";

        SqlConnection northwindConnection = new SqlConnection(connectionString);

        SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        return table;

    public static void Main()
        Application.Run(new Form1());
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Drawing
Imports System

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private WithEvents dataGridView1 As New DataGridView()
    Private bindingSource1 As New BindingSource()

    Public Sub New()

        Me.dataGridView1.Dock = DockStyle.Fill

    End Sub

    Private Sub InitializeDataGridView()
            ' Set up the DataGridView.
            With Me.dataGridView1
                ' Automatically generate the DataGridView columns.
                .AutoGenerateColumns = True

                ' Set up the data source.
                bindingSource1.DataSource = GetData("Select * From Products")
                .DataSource = bindingSource1

                ' Automatically resize the visible rows.
                .AutoSizeRowsMode = _

                ' Set the DataGridView control's border.
                .BorderStyle = BorderStyle.Fixed3D

                ' Put the cells in edit mode when user enters them.
                .EditMode = DataGridViewEditMode.EditOnEnter
            End With
        Catch ex As SqlException
            MessageBox.Show("To run this sample replace " _
                & "connection.ConnectionString with a valid connection string" _
                & "  to a Northwind database accessible to your system.", _
                "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Shared Function GetData(ByVal sqlCommand As String) _
        As DataTable

        Dim connectionString As String = _
            "Integrated Security=SSPI;Persist Security Info=False;" _
            & "Initial Catalog=Northwind;Data Source=localhost"

        Dim northwindConnection As SqlConnection = _
            New SqlConnection(connectionString)

        Dim command As New SqlCommand(sqlCommand, northwindConnection)
        Dim adapter As SqlDataAdapter = New SqlDataAdapter()
        adapter.SelectCommand = command

        Dim table As New DataTable
        table.Locale = System.Globalization.CultureInfo.InvariantCulture

        Return table

    End Function

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1)
    End Sub

End Class


DataGridViewクラスは、標準の Windows フォーム データ バインディング モデルをサポートしています。The DataGridView class supports the standard Windows Forms data-binding model. つまり、次のインターフェイスのいずれかを実装する任意の型のデータ ソースに指定できます。This means the data source can be of any type that implements one of the following interfaces:

具体的な例については、使用例」とこのセクションの最後に作業テーブルを参照してください。For specific examples, see the Example section and the task table at the end of this section.

通常、バインド、BindingSourceコンポーネントおよび bind、BindingSourceコンポーネントを別にデータ ソースまたはビジネス オブジェクトを設定します。Typically, you will bind to a BindingSource component and bind the BindingSource component to another data source or populate it with business objects. BindingSourceコンポーネントが優先されるデータ ソースでさまざまなデータ ソースにバインドでき、自動的に多くのデータ バインドの問題を解決することができます。The BindingSource component is the preferred data source because it can bind to a wide variety of data sources and can resolve many data binding issues automatically.

設定する必要がありますを複数のリストまたはテーブルを含むデータ ソースにバインドする際、DataMemberプロパティをリストまたはテーブルにバインドするを指定する文字列。When binding to a data source that contains multiple lists or tables, you must set the DataMember property to a string that specifies the list or table to bind to. バインドする場合、 BindingSource 、ただし、複数のリストまたはテーブルを含むコンポーネントを設定できます、DataMemberのプロパティ、BindingSourceコンポーネント代わりにします。When binding to a BindingSource component that contains multiple lists or tables, however, you can set the DataMember property of the BindingSource component instead.

データベースのデータではなく、オブジェクトのコレクションにバインドする場合は設定通常、DataSourceNullValueによって返されるオブジェクトのプロパティ、DefaultCellStyleプロパティをnullの既定値を使用するのではなくDBNull.Value、これはデータベースのデータに適しています。When binding to an object collection rather than to database data, you will typically set the DataSourceNullValue property of the object returned by the DefaultCellStyle property to null rather than using the default value of DBNull.Value, which is appropriate for database data.

詳細については、次を参照してください。 Windows フォームの DataGridView コントロールでのデータ表示します。For more information, see Displaying Data in the Windows Forms DataGridView Control. 次の表に、関連する一般的なタスクへの直接リンク、DataSourceプロパティ。The following table provides direct links to common tasks related to the DataSource property.

チュートリアル:フォームの DataGridView コントロールの 2 つの Windows を使用してマスター/詳細フォームを作成する方法。オブジェクトを Windows フォーム DataGridView コントロールにバインドします。See Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls and How to: Bind Objects to Windows Forms DataGridView Controls.