• 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
    • 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➡
      • 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

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,…

Update any Visio ShapeSheet cell with External Data

When Microsoft introduced a new way of linking external data to Visio shapes in 2007, I initially bemoaned the inability to update anything but Shape Data row values, unlike the old database add-on that I had been using for 10 years. The new method, though, has many advantages over the old way, not least that…

Keeping Visio Data Graphic Items Level

My good friend Scott Helmers, Visio author and trainer, of Harvard Computing Group , recently asked for some help in keeping data graphic items level when their target shape is rotated. Fortunately, I was able to assist, so I thought I would explain how this can be done, and also update my Icon Maker macro…

Duplicating Visio Data Graphics

I was recently asked about switching between different Visio Data Graphics within a page, so I thought I should record a few short videos to explain how Visio Data Graphics work, how they can be edited and duplicated, and how to automate switching between them. (more…)

Visio 2010 MVP Session videos reprise

Back in 2012, my fellow Visio MVPs, Scott Helmers and Chris Roth, and I recorded a series of 24 videos about Visio 2010. They were first hosted on Microsoft’s web site, then they put them up on YouTube, they they got deleted :-(. Well, we have managed to retrieve them, and put them back up…

Viewing Visio Document Changes in Git

Developing a Visio solution usually involves both .Net code and Visio ShapeSheet formulas. Good practice dictates that the source code is saved into a code repository, such as Git, where changes can be committed and commented. Visual Studio 2019 now includes native Git support, and can be linked to Azure DevOps easily. The code can…

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

Your email address will not be published. Required fields are marked *

Primary Sidebar

  • LinkedIn
  • Twitter

Recent Posts

  • Pushing Data Visualizer in Visio beyond its limits
  • Pushing Data Visualizer in Visio to the limits!
  • Teams Tuesday Podcast Recording about Visio
  • Linking Data to Visio Shapes in Code
  • Editing Visio Layer Colours with LayerManager

Categories

Tags

Accessibility Add-Ins Connectors Containers Data Export Data Graphics Data Import Data Visualizer Educational Excel GraphDatabase Hyperlinks Icon Sets JavaScript Layers Legend Link Data to Shapes Lists MSIgnite MVP Office365 Org Chart PowerApps PowerBI PowerQuery Processes Shape Data Shape Design ShapeSheet ShapeSheet Functions SharePoint 2013 SQL Teams Themes Validation VBA Video Visio Visio 2007 Visio 2013 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

  • LinkedIn
  • Twitter

Search this website

Recent posts

  • Pushing Data Visualizer in Visio beyond its limits
  • Pushing Data Visualizer in Visio to the limits!
  • Teams Tuesday Podcast Recording about Visio
  • Linking Data to Visio Shapes in Code
  • Editing Visio Layer Colours with LayerManager

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