• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

bVisual

  • Home
  • Services
    • How Visio smartness can help your business
    • Visio visual in Power BI
    • Visio Consulting Services
    • Visio Bureau Services
    • Visio Training and Support Services
  • Products
    • Visio Shape Report Converter
    • SS Plus
    • LayerManager
    • visViewer
    • Metro Icons
    • Rules Tools for Visio
    • The Visio 2010 Sessions App
    • Multi-Language Text for Visio
    • Document Imager for Visio
    • multiSelect for Visio
    • pdSelect for Visio
  • Case Studies
    • Case studies overview
    • Using Visio in Education for GIS
    • Visualizing Construction Project Schedules
    • Visio Online Business Process Mapping
    • Nexans Visio Template
    • CNEE Projects, WorldCom
    • Chase Manhattan Bank
  • News
    • Recent news
    • News archive
  • Resources
    • Articles➡
      • ShapeSheet Functions A-Z
      • Comparing Visio for the Web and Desktop
      • Customising Visio Shapes for the Web App
      • Key differences between the Visio desktop and web apps
      • Using the Visio Data Visualizer in Excel
      • Using Visio in Teams
      • Creating Visio Tabs and Apps for Teams with SharePoint Framework (SPFx)
      • Designing Power Automate Flows with Microsoft Visio
      • Innovative uses of Visio Lists
    • Webcasts ➡
      • Visio in Organizations
      • My session and other Visio sessions at MSIgnite 2019
      • Power up your Visio diagrams
      • Vision up your Visio diagrams
      • The Visio 2010 MVP Sessions
    • Visio Web Learning Resources
    • Books➡
      • Visualize Complex Processes with Microsoft Visio
      • Mastering Data Visualization with Microsoft Visio
      • Microsoft Visio Business Process Diagramming and Validation
      • Visualizing Information with Microsoft Visio
  • Blog
    • Browse blog articles
    • Visio Power BI articles
    • Visio for Web articles
    • A history of messaging and encryption
  • About us
    • About bVisual
    • Testimonials
    • Bio of David Parker
    • Contact Us
    • Website Privacy Policy
    • Website terms and conditions
    • Ariba Network
You are here: Home / Shape Design / External Data / Linking Data to Visio Shapes in Code

Published on November 2, 2022 by David Parker

Linking Data to Visio Shapes in Code

One of the most useful capabilities of Visio Professional and Visio Plan 2 is to link external data to shapes and have them refreshed by changes in the data source. So, many of my solutions involve writing code to make these links, and they are covered with some VBA examples in my book, Mastering Data Visualization with Microsoft Visio Professional 2016, but I mostly write C# code in VSTO add-ins, so I thought it would be useful to demonstrate how easy it is to create data links by dropping a shape, and by adding links to an existing shape. The book, by the way, is still relevant for the current Visio Professional and Visio Plan 2 editions!

I have uploaded a short video to YouTube to demonstrate and included the LinqPad code listings below.

DropLinkedPerson

This code uses the selected data recordset to drop a Person master shape in the centre of the page, linked to a specified person row.

void Main()
{
	var vApp = MyExtensions.GetRunningVisio();
	if (vApp.ActiveDocument == null) return;
	if (vApp.ActivePage == null) return;

	Visio.Window win = vApp.ActiveWindow;
	Visio.Document doc = vApp.ActiveDocument;
	Visio.Page pag = vApp.ActivePage;
	int DiagramServices = doc.DiagramServicesEnabled;
	doc.DiagramServicesEnabled = (int)Visio.VisDiagramServices.visServiceAll;

	Visio.Window winDrs = 
		win.Windows.ItemFromID[(int)Visio.VisWinTypes.visWinIDExternalData];
	
	if (winDrs.Visible)
	{
		Visio.DataRecordset drs = winDrs.SelectedDataRecordset;
		if (drs != null)
		{
			var criteria = $"[Name] = 'Jim Kim'" ;
			var mst = doc.Masters["Person"];
			var x = 0.5 * pag.PageSheet.CellsU["PageWidth"].ResultIU;
			var y = 0.5 * pag.PageSheet.CellsU["PageHeight"].ResultIU;
			Array rowIDs = drs.GetDataRowIDs(criteria);
			for (int i = 0; i < rowIDs.Length; i++)
			{
				var shp = pag.DropLinked(mst,x,y,
					drs.ID,(int) rowIDs.GetValue(i),true);
			}
		}
	}
	doc.DiagramServicesEnabled = DiagramServices;
}

DropLinkedDepartmentPersonnel

This code uses the selected data recordset to drop Person master shapes for each person from a specified department.

void Main()
{
	var vApp = MyExtensions.GetRunningVisio();
	if (vApp.ActiveDocument == null) return;
	if (vApp.ActivePage == null) return;

	Visio.Window win = vApp.ActiveWindow;
	Visio.Document doc = vApp.ActiveDocument;
	Visio.Page pag = vApp.ActivePage;
	int DiagramServices = doc.DiagramServicesEnabled;
	doc.DiagramServicesEnabled = (int)Visio.VisDiagramServices.visServiceAll;

	Visio.Window winDrs = 
		win.Windows.ItemFromID[(int)Visio.VisWinTypes.visWinIDExternalData];
	
	if (winDrs.Visible)
	{
		Visio.DataRecordset drs = winDrs.SelectedDataRecordset;
		if (drs != null)
		{
			var criteria = $"[Department] = 'Marketing'" ;
			var mst = doc.Masters["Person"];
			var x = 0.5 * pag.PageSheet.CellsU["PageWidth"].ResultIU;
			var y = 0.5 * pag.PageSheet.CellsU["PageHeight"].ResultIU;
			
			Array rowIDs = drs.GetDataRowIDs(criteria);
			if (rowIDs.Length > 0)
			{
				var dY = y / rowIDs.Length;
				var undoScope = vApp.BeginUndoScope("Dropping linked shapes");
				for (int i = 0; i < rowIDs.Length; i++)
				{
					var shp = pag.DropLinked(mst, x, y + (i * dY),
						drs.ID, (int)rowIDs.GetValue(i), true);
				}
				vApp.EndUndoScope(undoScope,true);
			}
		}
	}
	doc.DiagramServicesEnabled = DiagramServices;
}

DropLinkedPersonInRoom

This code uses the selected data recordset to add a data link to a simple shape with Office Number text which is used to get a person row.

void Main()
{
	var vApp = MyExtensions.GetRunningVisio();
	if (vApp.ActiveDocument == null) return;
	if (vApp.ActivePage == null) return;

	Visio.Window win = vApp.ActiveWindow;
	Visio.Document doc = vApp.ActiveDocument;
	Visio.Page pag = vApp.ActivePage;
	
	if (win.Selection.Count == 0)
	{
		return;
	}
	
	var shp = win.Selection.PrimaryItem;
	var shpText = shp.Characters.Text.ToString();
	
	int.TryParse(shpText, out int off_nmbr);
	
	if (off_nmbr == 0)
	{
		return;
	}
	
	int DiagramServices = doc.DiagramServicesEnabled;
	doc.DiagramServicesEnabled = (int)Visio.VisDiagramServices.visServiceAll;

	
	Visio.Window winDrs =
		win.Windows.ItemFromID[(int)Visio.VisWinTypes.visWinIDExternalData];
	
	
	if (winDrs.Visible)
	{
		Visio.DataRecordset drs = winDrs.SelectedDataRecordset;
		if (drs != null)
		{
			var criteria = $"[Office_Number] = {off_nmbr}" ;
			Array rowIDs = drs.GetDataRowIDs(criteria);
			for (int i = 0; i < rowIDs.Length; i++)
			{
				shp.LinkToData(drs.ID, (int) rowIDs.GetValue(i),true);
			}
		}
	}
	doc.DiagramServicesEnabled = DiagramServices;
}

DropLinkedPersonnelInRooms

This code uses the selected data recordset to add a data link to selected simple shapes with Office Number text which is used to get a person row for each.

void Main()
{
	var vApp = MyExtensions.GetRunningVisio();
	if (vApp.ActiveDocument == null) return;
	if (vApp.ActivePage == null) return;

	Visio.Window win = vApp.ActiveWindow;
	Visio.Document doc = vApp.ActiveDocument;
	Visio.Page pag = vApp.ActivePage;
	
	if (win.Selection.Count == 0)
	{
		return;
	}
	var sel = win.Selection;
	int DiagramServices = doc.DiagramServicesEnabled;
	doc.DiagramServicesEnabled = (int)Visio.VisDiagramServices.visServiceAll;

	Visio.Window winDrs = 
		win.Windows.ItemFromID[(int)Visio.VisWinTypes.visWinIDExternalData];
	
	if (winDrs.Visible)
	{
		Visio.DataRecordset drs = winDrs.SelectedDataRecordset;
		if (drs != null)
		{
			var undoScope = vApp.BeginUndoScope("Adding data links to shapes");
			foreach (Visio.Shape shp in sel)
			{
				var shpText = shp.Characters.Text.ToString();
				int.TryParse(shpText, out int off_nmbr);
				if (off_nmbr != 0)
				{
					var criteria = $"[Office_Number] = {off_nmbr}";
					Array rowIDs = drs.GetDataRowIDs(criteria);
					for (int i = 0; i < rowIDs.Length; i++)
					{
						shp.LinkToData(drs.ID, (int)rowIDs.GetValue(i), false);
					}
				}
			}
			vApp.EndUndoScope(undoScope, true);
		}
	}
	doc.DiagramServicesEnabled = DiagramServices;
}

Note that I do not recommend using the ApplyDataGraphicsAfterLink = true argument for this particular code because Visio can take a while to insert DataGraphics into each shape, but the foreach loop does not wait for the previous shp to finish its update.

GetRunningVisio

This is the extension to get the running Visio application.

// MyExtensions
using System;
using System.Runtime.InteropServices;
using LINQPad;
using Microsoft.Office.Interop.Visio;

public static Application GetRunningVisio()
{
	Application vApp = null;
	try
	{
		vApp = (Application)Marshal.GetActiveObject("Visio.Application");
	}
	catch (Exception ex)
	{
		Extensions.Dump<string>("Couldn't find running Visio instance", ex.Message);
	}
	return vApp;
}

Related posts

Co-authoring and Commenting with Visio Documents

Microsoft Visio can be used in the web browser and on the desktop, but there are several licensing options available, so which ones can be used concurrently whilst supporting co-authoring and commenting? This article tests the various scenarios but assumes that the Visio documents are stored in OneDrive for Business or SharePoint Online\Teams. The Microsoft…

Merging Linked Data from Similar Tables

I was recently asked how to link data from different tables but with similar column names to Visio shapes. In this case, each table has the same unique identifier, but some of the column names are the same. The problem is that the data linking matches the column name with the label of a Shape…

Linking Data to Shapes in Visio after using Data Visualizer

Data Visualizer (DV) in Visio Plan 2 (Data | Create from Data | Create ) is great because it provides a way of automatically creating a diagram from data, but it also prevents some of the other data-linking features in Visio from being used. This is because DV wants to take control of the data…

Using Visio Color by Value on Connectors

Data Graphics in Visio Plan 2 and Visio Professional is great, but it only enables us to use them with 2D shapes in Visio, i.e. not on connectors. So, what if you want to change the line colour of the connectors between the 2D shapes because of the data flowing between them? Well, it is…

Understanding Visio Data Graphic’s Color by Value

The desktop Visio editions, Visio Professional and Visio Plan 2, have a great way of automatically displaying data as Data Bars, Icon Sets, Text Callouts and Color by Value. The first three types of Data Graphics require sub-shapes to be inserted into each shape that they are applied to, but the last one, Color by…

Pushing Data Visualizer in Visio to the limits!

Regular readers of my blog will know that I like to use the Data Visualizer (DV) in Visio Plan 2, but I recently tried to help a user who really decided to push it to the limits. In this scenario, there were multiple connections, but with different labels, being created between the same flowchart shapes,…

Related

Filed Under: C#, Data Graphics, External Data, Shape Data Tagged With: Coding, External Data, Link Data to Shapes, Shape Data, Visio

About David Parker

David Parker has 25 years' experience of providing data visualization solutions to companies around the globe. He is a Microsoft MVP and Visio expert.

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

  • LinkedIn
  • Twitter

Recent Posts

  • Co-authoring and Commenting with Visio Documents
  • Fixing dimensions of 2D shapes
  • Merging Linked Data from Similar Tables
  • Smart Radio Buttons and Check Boxes in Visio
  • Using Button Face Ids in Visio

Categories

Tags

Accessibility Add-Ins Connectors Containers Data Export Data Graphics Data Import Data Visualizer Educational Excel GraphDatabase Hyperlinks Icon Sets JavaScript LayerManager Layers Legend Link Data to Shapes Lists MSIgnite MVP Office365 Org Chart PowerApps PowerBI PowerQuery Processes Setup and Deployment Shape Data Shape Design ShapeSheet ShapeSheet Functions SharePoint 2013 SQL Teams Validation VBA Video Visio Visio 2007 Visio for the Web Visio Online Visio Services Visio Viewer Webinar

Footer

bVisual Profile

The UK-based independent Visio consultancy with a worldwide reach. We have over 25 years experience of providing data visualization solutions to companies around the globe.

Learn more about bVisual

  • Amazon
  • E-mail
  • Facebook
  • LinkedIn
  • Twitter
  • YouTube

Search this website

Recent posts

  • Co-authoring and Commenting with Visio Documents
  • Fixing dimensions of 2D shapes
  • Merging Linked Data from Similar Tables
  • Smart Radio Buttons and Check Boxes in Visio
  • Using Button Face Ids in Visio

Copyright © 2025 · Executive Pro on Genesis Framework · WordPress · Log in