How to: Fill ListObject controls with data
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
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.
Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Excel. For more information, see Features available by Office application and project type.
To bind data to a ListObject control
Create a DataTable at the class level.
System.Data.DataTable table = new System.Data.DataTable("Employees");
Dim table As DataTable = New DataTable("Employees")
Add sample columns and data in the
Startup
event handler of theSheet1
class (in a document-level project) orThisAddIn
class (in an application-level project).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");
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")
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.
list1.AutoSetDataBoundColumnHeaders = true; list1.SetDataBinding(table, null, "LastName", "FirstName");
list1.AutoSetDataBoundColumnHeaders = True list1.SetDataBinding(table, Nothing, "LastName", "FirstName")
To disconnect the ListObject control from the data source
Call the Disconnect method of
List1
.list1.Disconnect();
list1.Disconnect()
Compile the code
This code example assumes you have an existing ListObject named list1
on the worksheet in which this code appears.
See also
- Extend Word documents and Excel workbooks in VSTO Add-ins at run time
- Controls on Office documents
- Add controls to Office documents at run time
- How to: Map ListObject columns to data
- Automate Excel by using extended objects
- ListObject control
- Bind data to controls in Office solutions
- How to: Populate worksheets with data from a database
- How to: Populate documents with data from services