DataGridView.DataSource 속성

정의

DataGridView에 데이터가 표시되는 데이터 소스를 가져오거나 설정합니다.

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

속성 값

표시할 DataGridView에 대한 데이터가 포함된 개체입니다.

예외

데이터 소스에서 오류가 발생했을 때 DataError 이벤트에 대한 처리기가 없거나 처리기에서 ThrowException 속성을 true로 설정한 경우. 예외 개체는 일반적으로 FormatException 형식으로 캐스팅할 수 있습니다.

예제

다음 코드 예제에서는 간단한 데이터 바인딩 DataGridView을 초기화하는 방법을 보여 줍니다. 또한 속성을 설정하는 방법도 보여 줍니다 DataSource .

#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
{
public:
   Form1()
      : Form()
   {
      
      //This call is required by the Windows Form Designer.
      InitializeComponent();
      InitializeDataGridView();
      
      //Add any initialization after the InitializeComponent() call
   }


protected:

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

private:
   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.

   [System::Diagnostics::DebuggerNonUserCode]
   void InitializeComponent()
   {
      this->dataGridView1 = gcnew System::Windows::Forms::DataGridView;
      this->bindingSource1 = gcnew System::Windows::Forms::BindingSource;
      this->SuspendLayout();

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

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

internal:

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

         return m_DefaultInstance;
      }
   }

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

   void InitializeDataGridView()
   {
      try
      {
         // 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 );
         System::Threading::Thread::CurrentThread->Abort();
      }
      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;
        this.Controls.Add(dataGridView1);
        InitializeDataGridView();
    }

    private void InitializeDataGridView()
    {
        try
        {
            // 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);
            System.Threading.Thread.CurrentThread.Abort();
        }
    }

    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;
        adapter.Fill(table);

        return table;
    }

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }
}
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Drawing
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
        Me.Controls.Add(Me.dataGridView1)
        InitializeDataGridView()

    End Sub

    Private Sub InitializeDataGridView()
        Try
            ' 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 = _
                    DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders

                ' 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)
            System.Threading.Thread.CurrentThread.Abort()
        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
        adapter.Fill(table)

        Return table

    End Function

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

End Class

설명

클래스는 DataGridView 표준 Windows Forms 데이터 바인딩 모델을 지원합니다. 즉, 데이터 원본은 다음 인터페이스 중 하나를 구현하는 모든 형식일 수 있습니다.

특정 예제는 이 섹션의 끝에 있는 예제 섹션 및 작업 테이블을 참조하세요.

일반적으로 BindingSource 구성 요소에 바인딩하고 BindingSource 구성 요소를 다른 데이터 원본에 바인딩하거나 비즈니스 개체로 채웁니다. BindingSource 구성 요소는 다양한 데이터 원본에 바인딩할 수 있고 많은 데이터 바인딩 문제를 자동으로 해결할 수 있기 때문에 기본 설정 데이터 원본입니다.

여러 목록 또는 테이블이 포함된 데이터 원본에 바인딩할 때는 속성을 바인딩할 목록 또는 테이블을 지정하는 문자열로 설정 DataMember 해야 합니다. 그러나 여러 목록 또는 테이블을 포함하는 구성 요소에 바인딩하는 BindingSource 경우 구성 요소의 BindingSource 속성을 대신 설정할 DataMember 수 있습니다.

데이터베이스 데이터가 아닌 개체 컬렉션에 바인딩하는 경우 일반적으로 데이터베이스 데이터에 적합한 의 기본값을 사용하는 대신 속성에서 반환 DefaultCellStyle 된 개체의 DBNull.Value속성을 null 로 설정합니다DataSourceNullValue.

자세한 내용은 Windows Forms DataGridView 컨트롤에서 데이터 표시를 참조하세요. 다음 표에서는 속성과 관련된 DataSource 일반적인 작업에 대한 직접 링크를 제공합니다.

연습: 두 Windows Forms DataGridView 컨트롤을 사용하여 마스터/세부 정보 양식 만들기방법: 개체를 Windows Forms DataGridView 컨트롤에 바인딩을 참조하세요.

적용 대상

추가 정보