다음을 통해 공유


연습: Word 작업 창의 컨트롤에 데이터 바인딩

이 연습에서는 Microsoft Office Word의 작업 창에 있는 컨트롤에 데이터를 바인딩하는 방법을 보여 줍니다. 컨트롤은 SQL Server 데이터베이스에 있는 테이블 간의 마스터/세부 관계를 나타냅니다.

적용 대상: 이 항목의 정보는 Word 2007 및 Word 2010의 문서 수준 프로젝트에 적용됩니다. 자세한 내용은 Office 응용 프로그램 및 프로젝트 형식에 따라 사용 가능한 기능을 참조하십시오.

이 연습에서는 다음 작업을 수행합니다.

  • 데이터에 바인딩되는 Windows Forms 컨트롤이 포함된 작업 창 만들기

  • 마스터/세부 관계를 사용하여 컨트롤에 데이터 표시

  • 응용 프로그램을 열 때 작업 창 표시

참고

일부 Visual Studio 사용자 인터페이스 요소의 경우 다음 지침에 설명된 것과 다른 이름 또는 위치가 시스템에 표시될 수 있습니다. 설치한 Visual Studio 버전과 사용하는 설정에 따라 이러한 요소가 결정됩니다. 자세한 내용은 설정에 대한 작업을 참조하십시오.

사전 요구 사항

이 연습을 완료하려면 다음 구성 요소가 필요합니다.

-

Microsoft Office 개발자 도구를 포함하는 Visual Studio 2010 버전입니다. 자세한 내용은 [Office 솔루션을 개발할 수 있도록 컴퓨터 구성](bb398242\(v=vs.100\).md)을 참조하십시오.
  • Word 2007 또는 Word 2010

  • Northwind SQL Server 샘플 데이터베이스가 있는 서버에 액세스할 수 있어야 합니다.

  • SQL Server 데이터베이스에서 읽고 쓰기 위한 권한이 있어야 합니다.

프로젝트 만들기

첫 번째 단계에서는 Word 문서 프로젝트를 만듭니다.

새 프로젝트를 만들려면

  • 이름이 My Word Actions Pane인 Word 문서 프로젝트를 만듭니다. 마법사에서 새 문서 만들기를 선택합니다.

    자세한 내용은 방법: Visual Studio에서 Office 프로젝트 만들기를 참조하십시오.

    Visual Studio의 디자이너에 새 Word 문서가 열리고 My Word Actions Pane 프로젝트가 솔루션 탐색기에 추가됩니다.

작업 창에 컨트롤 추가

이 연습에서는 데이터 바인딩된 Windows Forms 컨트롤이 포함된 작업 창 컨트롤이 필요합니다. 데이터 소스를 프로젝트에 추가한 다음 데이터 소스 창에서 작업 창 컨트롤로 컨트롤을 끌어 놓습니다.

작업 창 컨트롤을 추가하려면

  1. 솔루션 탐색기에서 My Word Actions Pane 프로젝트를 선택합니다.

  2. 프로젝트 메뉴에서 새 항목 추가를 클릭합니다.

  3. 새 항목 추가 대화 상자에서 작업 창 컨트롤을 선택하고 이름을 ActionsControl로 지정한 다음 추가를 클릭합니다.

프로젝트에 새 데이터 소스를 추가하려면

  1. 데이터 소스 창이 표시되지 않으면 데이터 메뉴에서 데이터 소스 표시를 클릭합니다.

    참고

    데이터 소스 표시를 사용할 수 없으면 Word 문서를 클릭한 다음 다시 확인합니다.

  2. 새 데이터 소스 추가를 클릭하여 데이터 소스 구성 마법사를 시작합니다.

  3. 데이터베이스를 선택하고 다음을 클릭합니다.

  4. Northwind 샘플 SQL Server 데이터베이스에 대한 데이터 연결을 선택하거나 새 연결 단추를 사용하여 새 연결을 추가합니다.

  5. 다음을 클릭합니다.

  6. 연결을 저장하는 옵션이 선택되어 있는 경우 선택을 취소하고 다음을 클릭합니다.

  7. 데이터베이스 개체 창에서 테이블 노드를 확장합니다.

  8. SuppliersProducts 테이블 옆에 있는 확인란을 선택합니다.

  9. 마침을 클릭합니다.

마법사에서 Suppliers 테이블과 Products 테이블이 데이터 소스 창에 추가됩니다. 솔루션 탐색기에 표시되는 프로젝트에 형식화된 데이터 집합도 추가됩니다.

작업 창 컨트롤에 데이터 바인딩된 Windows Forms 컨트롤을 추가하려면

  1. 데이터 소스 창에서 Suppliers 테이블을 확장합니다.

  2. Company Name 노드에서 드롭다운 화살표를 클릭하고 ComboBox를 선택합니다.

  3. CompanyName데이터 소스 창에서 작업 창 컨트롤에 끌어 놓습니다.

    작업 창 컨트롤에 ComboBox 컨트롤이 작성됩니다. 이와 함께 SuppliersBindingSource라는 BindingSource, 테이블 어댑터 및 DataSet이 구성 요소 트레이에서 프로젝트에 추가됩니다.

  4. 구성 요소 트레이에서 SuppliersBindingNavigator를 선택하고 Delete 키를 누릅니다. 이 연습에서는 SuppliersBindingNavigator를 사용하지 않습니다.

    참고

    SuppliersBindingNavigator를 삭제해도 이와 관련하여 생성된 모든 코드는 제거되지 않습니다. 이 코드를 직접 제거할 수 있습니다.

  5. 콤보 상자를 레이블 아래로 옮기고 Size 속성을 171, 21로 변경합니다.

  6. 데이터 소스 창에서 Suppliers 표의 자식인 Products 표를 확장합니다.

  7. ProductName 노드에서 드롭다운 화살표를 클릭하고 ListBox를 선택합니다.

  8. ProductName을 작업 창 컨트롤에 끌어 놓습니다.

    작업 창 컨트롤에 ListBox 컨트롤이 작성됩니다. 이와 함께 ProductBindingSource라는 BindingSource와 테이블 어댑터가 구성 요소 트레이에서 프로젝트에 추가됩니다.

  9. 목록 상자를 레이블 아래로 옮기고 Size 속성을 171,95로 변경합니다.

  10. Button도구 상자에서 작업 창 컨트롤로 끌어 목록 상자 아래에 배치합니다.

  11. Button을 마우스 오른쪽 단추로 클릭하고 바로 가기 메뉴에서 속성을 클릭한 후 다음 속성을 변경합니다.

    Property

    Name

    Insert

    Text

    Insert

  12. 컨트롤에 맞도록 사용자 정의 컨트롤의 크기를 조정합니다.

데이터 소스 설정

데이터 소스를 설정하려면 작업 창 컨트롤의 Load 이벤트에 컨트롤을 DataTable의 데이터로 채우는 코드를 추가하고 각 컨트롤의 DataSourceDataMember 속성을 설정합니다.

데이터와 함께 컨트롤을 로드하려면

  1. ActionsControl 클래스의 Load 이벤트 처리기에 다음 코드를 추가합니다.

    Private Sub ActionsControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Load
    
        Me.SuppliersTableAdapter.Fill(Me.NorthwindDataSet.Suppliers)
        Me.ProductsTableAdapter.Fill(Me.NorthwindDataSet.Products)
    End Sub
    
    private void ActionsControl_Load(object sender, EventArgs e)
    {
        this.suppliersTableAdapter.Fill(this.northwindDataSet.Suppliers);
        this.productsTableAdapter.Fill(this.northwindDataSet.Products);
    }
    
  2. C#에서는 Load 이벤트에 이벤트 처리기를 연결해야 합니다. 이 코드를 ActionsControl 생성자에서 InitializeComponent에 대한 호출 밑에 배치할 수 있습니다. 이벤트 처리기를 만드는 방법에 대한 자세한 내용은 방법: Office 프로젝트에서 이벤트 처리기 만들기를 참조하십시오.

    this.Load += new EventHandler(ActionsControl_Load);
    

컨트롤의 데이터 바인딩 속성을 설정하려면

  1. CompanyNameComboBox 컨트롤을 선택합니다.

  2. 속성 창에서 DataSource 속성의 오른쪽에 있는 단추를 클릭하고 suppliersBindingSource를 선택합니다.

  3. DisplayMember 속성의 오른쪽에 있는 단추를 클릭하고 CompanyName을 선택합니다.

  4. DataBindings 속성을 확장하고 Text 속성의 오른쪽에 있는 단추를 클릭한 다음 없음을 선택합니다.

  5. ProductNameListBox 컨트롤을 선택합니다.

  6. 속성 창에서 DataSource 속성의 오른쪽에 있는 단추를 클릭하고 productsBindingSource를 선택합니다.

  7. DisplayMember 속성의 오른쪽에 있는 단추를 클릭하고 ProductName을 선택합니다.

  8. DataBindings 속성을 확장하고 SelectedValue 속성의 오른쪽에 있는 단추를 클릭한 다음 없음을 선택합니다.

표에 데이터를 삽입하기 위한 메서드 추가

다음 작업에서는 바인딩된 컨트롤의 데이터를 읽어 Word 문서의 표를 채웁니다. 먼저 표의 머리글 서식을 지정하는 프로시저를 만든 다음 AddData 메서드를 추가하여 Word 표를 만들고 서식을 지정합니다.

표 머리글을 서식 지정하려면

  • ActionsControl 클래스에서 표의 머리글을 서식 지정하는 메서드를 만듭니다.

    Shared Sub SetHeadings(ByVal tblCell As Word.Cell, ByVal text As String)
    
        With tblCell.Range
            .Text = text
            .Font.Bold = True
            .ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
        End With
    End Sub
    
    static void SetHeadings(Microsoft.Office.Interop.Word.Cell tblCell, string text)
    {
        tblCell.Range.Text = text;
        tblCell.Range.Font.Bold = 1;
        tblCell.Range.ParagraphFormat.Alignment = 
            Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
    }
    

표를 만들려면

  • ActionsControl 클래스에서 표가 하나도 없는 경우 표를 만드는 메서드를 작성하고 작업 창의 데이터를 표에 추가합니다.

    Private Sub AddData(ByVal row As System.Data.DataRow, ByVal companyName As String)
    
        ' Create a table if it doesn't already exist.
        If Globals.ThisDocument.Tables.Count = 0 Then
    
            Try
                ' Create a table. 
                Dim tbl As Word.Table = Globals.ThisDocument.Tables.Add( _
                    Globals.ThisDocument.Application.Selection.Range, 1, 4)
    
                ' Insert headings.
                SetHeadings(tbl.Cell(1, 1), "Company Name")
                SetHeadings(tbl.Cell(1, 2), "Product Name")
                SetHeadings(tbl.Cell(1, 3), "Quantity")
                SetHeadings(tbl.Cell(1, 4), "Unit Price")
    
            Catch ex As Exception
                MessageBox.Show("Problem creating Products table: " & ex.Message, _
                    "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    
        ' Add data from data row to the table.
        Dim selection As Word.Selection = Globals.ThisDocument.Application.Selection
    
        If selection.Tables.Count > 0 Then
    
            Dim newRow As Word.Row = Globals.ThisDocument.Tables(1).Rows.Add()
            With newRow
                .Range.Font.Bold = False
                .Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
                .Cells(4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
                .Cells(1).Range.Text = companyName
                .Cells(2).Range.Text = row.Item("ProductName").ToString
                .Cells(3).Range.Text = row.Item("QuantityPerUnit").ToString
                .Cells(4).Range.Text = Math.Round(row.Item("UnitPrice"), 2)
            End With
    
        Else
            MessageBox.Show("Cursor must be within a table.", _
                "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Sub
    
    private void AddData(System.Data.DataRow row, string companyName)
    {
        object missing = System.Type.Missing;
    
        // Create a table if it doesn't already exist.
        if (Globals.ThisDocument.Tables.Count == 0)
        {
            try
            {
                // Create a table.
                Microsoft.Office.Interop.Word.Table tbl = Globals.ThisDocument.Tables.Add
                    (Globals.ThisDocument.Application.Selection.Range, 1, 4, ref missing, ref missing);
    
                // Insert headings.
                SetHeadings(tbl.Cell(1, 1), "Company Name");
                SetHeadings(tbl.Cell(1, 2), "Product Name");
                SetHeadings(tbl.Cell(1, 3), "Quantity");
                SetHeadings(tbl.Cell(1, 4), "Unit Price");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem creating Products table: " + ex.Message, 
                    "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    
        // Add data from data row to the table.
        Microsoft.Office.Interop.Word.Selection selection = Globals.ThisDocument.Application.Selection;
    
        if (selection.Tables.Count > 0)
        {
            Microsoft.Office.Interop.Word.Row newRow = Globals.ThisDocument.Tables[1].Rows.Add(ref missing);
    
            newRow.Range.Font.Bold = 0;
    
            newRow.Range.ParagraphFormat.Alignment = 
                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
    
            newRow.Cells[4].Range.ParagraphFormat.Alignment =
                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
    
            newRow.Cells[1].Range.Text = companyName;
            newRow.Cells[2].Range.Text = row["ProductName"].ToString();
            newRow.Cells[3].Range.Text = row["QuantityPerUnit"].ToString();
            newRow.Cells[4].Range.Text = Math.Round(Convert.ToDouble(row["UnitPrice"])).ToString("#,##0.00");
        }
        else
        {
            MessageBox.Show("Cursor must be within a table.", 
                "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    

Word 표에 텍스트를 삽입하려면

  1. 삽입 단추의 Click 이벤트 처리기에 다음 코드를 추가합니다.

    Private Sub Insert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Insert.Click
    
        Dim tbl As System.Data.DataTable = NorthwindDataSet.Products
        Dim rows() As System.Data.DataRow
    
        ' Check if a product is selected.
        If Not Me.ProductNameListBox.SelectedIndex < 0 Then
    
            Dim product As String = Me.ProductNameListBox.SelectedItem.Row.Item("ProductName")
            Dim company As String = Me.CompanyNameComboBox.Text
    
            ' Return the data row from the selected Product in the list box.
            rows = tbl.Select("[ProductName] = '" & product.Replace("'", "''") & "'")
    
            AddData(rows(0), company)
    
        Else
            MessageBox.Show("Please select a product.", "Actions Pane", MessageBoxButtons.OK)
        End If
    End Sub
    
    private void Insert_Click(object sender, System.EventArgs e)
    {
        System.Data.DataTable tbl = northwindDataSet.Products;
        System.Data.DataRow[] rows;
    
        // Check if a product is selected.
        if (this.productNameListBox.SelectedIndex >= 0)
        {
            System.Data.DataRowView productRow = (System.Data.DataRowView)this.productNameListBox.SelectedItem;
    
            string product = productRow.Row["ProductName"].ToString();
            string company = this.companyNameComboBox.Text;
    
            // Return the data row from the selected product.
            rows = tbl.Select("[ProductName] = '" + product.Replace("'", "''") + "'");
    
            this.AddData(rows[0], company);
        }
        else
        {
            MessageBox.Show("Please select a product.", "Actions Pane", MessageBoxButtons.OK);
        }
    }
    
  2. C#의 경우 단추의 Click 이벤트에 대한 이벤트 처리기를 만듭니다. ActionsControl 클래스의 Load 이벤트 처리기에 이 코드를 넣을 수 있습니다.

    this.Insert.Click += new EventHandler(Insert_Click);
    

작업 창 표시

작업 창은 컨트롤을 추가한 후에 표시됩니다.

작업 창을 표시하려면

  1. 솔루션 탐색기에서 마우스 오른쪽 단추로 ThisDocument.vb 또는 ThisDocument.cs를 클릭한 다음 바로 가기 메뉴에서 코드 보기를 클릭합니다.

  2. 다음 예제와 같이 ThisDocument 클래스의 맨 위에 컨트롤의 새 인스턴스를 만듭니다.

    Dim actions As New ActionsControl
    
    private ActionsControl actions = new ActionsControl();
    
  3. 다음 예제와 같이 ThisDocument의 Startup 이벤트 처리기에 코드를 추가합니다.

    Me.ActionsPane.Controls.Add(actions)
    
    this.ActionsPane.Controls.Add(actions);
    

응용 프로그램 테스트

이제 문서를 테스트하여 문서를 열 때 작업 창이 함께 나타나는지 확인할 수 있습니다. 작업 창의 컨트롤에서 마스터/세부 관계를 테스트하고 삽입 단추를 클릭할 때 Word 표에 데이터가 채워지는지 확인합니다.

문서를 테스트하려면

  1. F5 키를 눌러 프로젝트를 실행합니다.

  2. 작업 창이 표시되는지 확인합니다.

  3. 콤보 상자에서 회사를 선택하고 Products 목록 상자의 항목이 변경되는지 확인합니다.

  4. 제품을 선택하고 작업 창에서 삽입을 클릭하여 제품 세부 사항이 Word의 표에 추가되는지 확인합니다.

  5. 여러 회사의 다른 제품을 삽입합니다.

다음 단계

이 연습에서는 Word의 작업 창에 있는 컨트롤에 데이터를 바인딩하는 기본적인 방법을 보여 줍니다. 이후에 수행할 수 있는 작업은 다음과 같습니다.

참고 항목

작업

방법: Word 문서에 작업 창 추가

기타 리소스

작업 창 개요

Office 솔루션의 컨트롤에 데이터 바인딩