This project has moved. For the latest updates, please go here.

NamedRanges.Contains pick other NamedRange if one doesnt exist

Aug 2, 2013 at 8:30 AM
Hi, I am opening a spreadsheet and looking for particular namedrange say "PeopleData"

a recent change to the spreadsheet template has updated the name to "AllPeopleData"

I want to check on runtime that if "PeopleData" doesn't exist use the other namedrange "AllPeopleData"

I have to keep both for compatibility purpose...
c#

if (Workbook.NamedRanges.Contains("PeopleData"))
   use this 
else
   use "AllPeopleData"
Aug 4, 2013 at 7:52 PM
Do you have a question?
What you have posted is not valid C# code.
Are you looking for the actual C# code that would retrieve the correct range?
Aug 5, 2013 at 1:52 PM
roberttanenbaum wrote:
Do you have a question? yes, see answer 3
What you have posted is not valid C# code. sorry :(
Are you looking for the actual C# code that would retrieve the correct range? yes please the contains function looks for ixl range object....I am having trouble passing that....
thanks
Coordinator
Aug 5, 2013 at 2:36 PM
I think you can use ws.NamedRange("Name") and it will return null if it doesn't exist but I'll add a clearer way.
Coordinator
Aug 6, 2013 at 2:48 AM
Pick up the latest check-in...
Aug 6, 2013 at 10:46 AM
@MDeleon, I did try to use that but instead of returning a null, it raises an exception with the message like "The given key is not found"
Coordinator
Aug 6, 2013 at 1:46 PM
Edited Aug 6, 2013 at 1:47 PM
The following works fine (the ranges end up being null and the contains are false):
            var wb = new XLWorkbook();
            var ws = wb.AddWorksheet("Sheet1");
            var range1 = ws.NamedRange("Bad");
            var contains1 = ws.NamedRanges.Contains("Bad");
            IXLNamedRange range2;
            var contains2 = ws.NamedRanges.TryGetValue("Bad", out range2);
Aug 8, 2013 at 9:21 AM
Thanks MDeLeon but the codes you've provided are still throwing following exceptions

var range1 = ws.NamedRange("Bad");
ex = {"The given key was not present in the dictionary."}

var contains1 = ws.NamedRanges.Contains("Bad");
ex = {"Index was outside the bounds of the array."}

At the moment I've done a work around by getting all NamedRanges in a string collection then doing a Contains
Coordinator
Aug 8, 2013 at 1:11 PM
You have to get the source code and compile it.