Microsoft Visual Studio Tools for the Microsoft Office system (version 3.0)
How to: Fill ListObject Controls with Data

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Document-level projects

  • Excel 2007

  • Excel 2003

Application-level projects

  • Excel 2007

For more information, see Features Available by Application and Project Type.

You can use data binding as a way to quickly add data to your document. After binding data to a list object, you can disconnect the list object so it displays the data but is no longer bound to the data source.

link to video For a related video demonstration, see How Do I: Create a List in Excel that is Connected to a SharePoint List?.

To bind data to a ListObject control

  1. Create a DataTable at the class level.

    Visual Basic
    Dim table As DataTable = New DataTable("Employees")
    
    C#
    System.Data.DataTable table = new System.Data.DataTable("Employees");
    
  2. Add sample columns and data in the Startup event handler of the Sheet1 class (in a document-level project) or ThisAddIn class (in an application-level project).

    Visual Basic
    table.Columns.Add("FirstName", GetType(String))
    table.Columns.Add("LastName", GetType(String))
    table.Columns.Add("Title", GetType(String))
    
    table.Rows.Add("Nancy", "Anderson", "Sales Representative")
    table.Rows.Add("Robert", "Brown", "Sales Representative")
    
    C#
    table.Columns.Add("FirstName", typeof(string));
    table.Columns.Add("LastName", typeof(string));
    table.Columns.Add("Title", typeof(string));
    
    table.Rows.Add("Nancy", "Anderson", "Sales Representative");
    table.Rows.Add("Robert", "Brown", "Sales Representative");
    
  3. Call the SetDataBinding method and pass in the column names in the order they should appear. The order of the columns in the list object can differ from the order in which they appear in the DataTable.

    Visual Basic
    list1.AutoSetDataBoundColumnHeaders = True
    list1.SetDataBinding(table, Nothing, "LastName", "FirstName")
    
    C#
    list1.AutoSetDataBoundColumnHeaders = true;
    list1.SetDataBinding(table, null, "LastName", "FirstName");
    

To disconnect the ListObject control from the data source

  • Call the Disconnect method of List1.

    Visual Basic
    list1.Disconnect()
    
    C#
    list1.Disconnect();
    
Compiling the Code

This code example assumes you have an existing ListObject named list1 on the worksheet in which this code appears.

See Also

Tasks

Concepts

Other Resources

Tags :


Page view tracker