방법: Windows Forms DataGridView 컨트롤에 DataView 개체 바인딩

DataGridView 컨트롤에서는 데이터를 표 형식으로 표시하는 강력하고 유연한 방법을 제공합니다. DataGridView 컨트롤은 표준 Windows Forms 데이터 바인딩 모델을 지원하므로 DataView 및 다양한 데이터 소스에 바인딩합니다. 그러나 대부분의 경우 데이터 소스와의 상호 작용에 대한 세부 사항을 관리하는 BindingSource 구성 요소에 바인딩합니다.

DataGridView 컨트롤에 대한 자세한 내용은 DataGridView 컨트롤 개요를 참조하세요.

DataGridView 컨트롤을 DataView에 연결하려면

  1. 데이터베이스에서 데이터를 검색하는 세부 과정을 처리하는 메서드를 구현합니다. 다음 코드 예제에서는 GetData 구성 요소를 초기화한 다음 이 구성 요소를 사용하여 SqlDataAdapter을 채우는 DataSet 메서드를 구현합니다. connectionString 변수를 사용자의 데이터베이스에 적합한 값으로 설정해야 합니다. AdventureWorks SQL Server 샘플 데이터베이스가 설치된 서버에 액세스해야 합니다.

    void GetData()
    {
        try
        {
            // Initialize the DataSet.
            _dataSet = new DataSet
            {
                Locale = CultureInfo.InvariantCulture
            };
    
            // Create the connection string for the AdventureWorks sample database.
            const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
                + "Integrated Security=true;";
    
            // Create the command strings for querying the Contact table.
            const string contactSelectCommand = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact";
    
            // Create the contacts data adapter.
            _contactsDataAdapter = new SqlDataAdapter(
                contactSelectCommand,
                connectionString);
    
            // Create a command builder to generate SQL update, insert, and
            // delete commands based on the contacts select command. These are used to
            // update the database.
            var contactsCommandBuilder = new SqlCommandBuilder(_contactsDataAdapter);
    
            // Fill the data set with the contact information.
            _contactsDataAdapter.Fill(_dataSet, "Contact");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    
    Private Sub GetData()
        Try
            ' Initialize the DataSet.
            dataSet = New DataSet()
            dataSet.Locale = CultureInfo.InvariantCulture
    
            ' Create the connection string for the AdventureWorks sample database.
            Dim connectionString As String = "Data Source=localhost;Initial Catalog=AdventureWorks;" _
                    & "Integrated Security=true;"
    
            ' Create the command strings for querying the Contact table.
            Dim contactSelectCommand As String = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact"
    
            ' Create the contacts data adapter.
            contactsDataAdapter = New SqlDataAdapter( _
                contactSelectCommand, _
                connectionString)
    
            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on the contacts select command. These are used to
            ' update the database.
            Dim contactsCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(contactsDataAdapter)
    
            ' Fill the data set with the contact information.
            contactsDataAdapter.Fill(dataSet, "Contact")
    
        Catch ex As SqlException
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    
  2. 폼의 Load 이벤트 처리기에서 DataGridView 컨트롤을 BindingSource 구성 요소에 바인딩한 다음 GetData 메서드를 호출하여 데이터베이스에서 데이터를 검색합니다. Contact DataTable에 대한 LINQ to DataSet 쿼리에서 DataView가 만들어진 다음 BindingSource 구성 요소에 바인딩됩니다.

    void Form1_Load(object sender, EventArgs e)
    {
        // Connect to the database and fill the DataSet.
        GetData();
    
        contactDataGridView.DataSource = contactBindingSource;
    
        // Create a LinqDataView from a LINQ to DataSet query and bind it
        // to the Windows forms control.
        EnumerableRowCollection<DataRow> contactQuery = from row in _dataSet.Tables["Contact"].AsEnumerable()
                                                        where row.Field<string>("EmailAddress") != null
                                                        orderby row.Field<string>("LastName")
                                                        select row;
    
        _contactView = contactQuery.AsDataView();
    
        // Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = _contactView;
        contactDataGridView.AutoResizeColumns();
    }
    
    Private Sub Form1_Load(ByVal sender As System.Object, _
                           ByVal e As System.EventArgs) _
                           Handles MyBase.Load
        ' Connect to the database and fill the DataSet.
        GetData()
    
        contactDataGridView.DataSource = contactBindingSource
    
        ' Create a LinqDataView from a LINQ to DataSet query and bind it 
        ' to the Windows forms control.
        Dim contactQuery = _
            From row In dataSet.Tables("Contact").AsEnumerable() _
            Where row.Field(Of String)("EmailAddress") <> Nothing _
            Order By row.Field(Of String)("LastName") _
            Select row
    
        contactView = contactQuery.AsDataView()
    
        ' Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = contactView
        contactDataGridView.AutoResizeColumns()
    End Sub
    

참고 항목