http://msdn.microsoft.com/ko-kr/library/s7za025w(VS.80).aspx

방법: Windows Forms DataGridView 컨트롤에 데이터 바인딩

DataGridView 컨트롤은 표준 Windows Forms 데이터 바인딩 모델을 지원하므로 다양한 데이터 소스에 바인딩됩니다. 그러나, 대부분의 환경에서는 데이터 소스와의 상호 작용에 대한 세부 사항을 관리하는 BindingSource 구성 요소에 바인딩합니다.

private void GetData(string selectCommand)
{
    try
    {
        // Specify a connection string. Replace the given value with a
        // valid connection string for a Northwind SQL Server sample
        // database accessible to your system.
        String connectionString =
            "Integrated Security=SSPI;Persist Security Info=False;" +
            "Initial Catalog=Northwind;Data Source=localhost";

        // Create a new data adapter based on the specified query.
        dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

        // Create a command builder to generate SQL update, insert, and
        // delete commands based on selectCommand. These are used to
        // update the database.
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

        // Populate a new data table and bind it to the BindingSource.
        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;
        dataAdapter.Fill(table);
        bindingSource1.DataSource = table;

        // Resize the DataGridView columns to fit the newly loaded content.
        dataGridView1.AutoResizeColumns(
            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
    }
    catch (SqlException)
    {
        MessageBox.Show("To run this example, replace the value of the " +
            "connectionString variable with a connection string that is " +
            "valid for your system.");
    }
}

*참고

BindingSource

구성 요소는 두 가지 용도로 사용됩니다. 먼저 간접 참조 계층, 통화 관리, 변경 알림 및 기타 서비스를 제공하여 폼의 컨트롤을 데이터에 바인딩하는 과정을 단순화합니다. 이 작업은 데이터 소스에 BindingSource 구성 요소를 연결하고 폼의 컨트롤을 BindingSource 구성 요소에 바인딩하는 방식으로 수행됩니다. 탐색, 정렬, 필터링 및 업데이트를 비롯한 데이터와의 추가 상호 작용은 모두 BindingSource 구성 요소를 호출하여 수행됩니다.

BindingSource에서는 내부 데이터에 액세스하기 위한 멤버를 제공합니다. 현재 항목은 Current 속성을 통해 검색할 수 있으며 목록 전체는 List 속성을 통해 검색할 수 있습니다. 현재 항목에 대한 편집 작업은 Current 속성과 RemoveCurrent, EndEdit, CancelEdit, AddAddNew 메서드를 통해 지원됩니다. 통화 관리는 모든 내부 데이터 소스 형식에 대해 자동으로 처리되지만 이 클래스는 사용자 지정할 수 있는 CurrentItemChangedDataSourceChanged 등의 여러 이벤트를 노출합니다.

목록 내의 항목을 탐색하기 위해 VCR과 비슷한 UI(사용자 인터페이스)를 제공하는 BindingNavigator 클래스를 사용하여 BindingSource 구성 요소에 바인딩된 데이터 소스를 탐색하거나 관리할 수도 있습니다. BindingNavigator는 모든 데이터 소스에 바인딩될 수 있지만 BindingNavigator.BindingSource 속성을 통해 BindingSource 구성 요소와 통합되도록 디자인되어 있습니다.

+ Recent posts