Friday, November 25, 2011

Get Selected Layer From TOC (ArcObjects)

Getting the selected layer a user is using can be an easy way to have the user interact with ArcMap without having them mull through some form.  This is be achieved in a couple of line of code:

IContentsView contentsView = mapDocument.CurrentContentsView;
object selectedItem = contentsView.SelectedItem;
if (!(selectedItem is ILayer))

First the code assumes you know how to get the current map document's reference and second it not only gets the selected item, I provided a simple check that ensures it's a layer object.