Domanda

I am trying to iterate through each web and its webs, to get the list of child webs and so on, but problem is, when iteration comes to a web which doesn't have any sub webs it gives an exception

Object Reference not set to an instance of an object

Code is here

  private void dwnEachWeb(SPWeb TopLevelWeb)
    {
        if (TopLevelWeb.Webs != null)
        {
            dwnEachList(TopLevelWeb);
        }
        foreach (SPWeb ChildWeb in TopLevelWeb.Webs)
        {
            dwnEachWeb(ChildWeb);
            ChildWeb.Dispose();
        }
    }

I even tried "if (TopLevelWeb.Webs.Counts == 0)" but problem is, when there will be no subwebs then how program will gonna check if its zero or null, i wonder if there is any way i can check if a web has collection of webs , like if i can check web.webs exists or not.

È stato utile?

Soluzione

You'll get the null reference exception when TopLevelWeb.Webs evaluates to null. So try:

private void dwnEachWeb(SPWeb TopLevelWeb)
{
    if (TopLevelWeb != null && TopLevelWeb.Webs != null)
    {
        dwnEachList(TopLevelWeb);

        foreach (SPWeb ChildWeb in TopLevelWeb.Webs)
        {
            dwnEachWeb(ChildWeb);
            ChildWeb.Dispose();
        }
    }
}

This only does the foreach if TopLevelWeb and TopLevelWeb.Webs is not null.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top