Question

How to check if there are users in the group or not?

        string groupName = "Home members";

        using (SPSite Site = new SPSite("http://sp/sites/test"))
        {
            using (SPWeb web = Site.OpenWeb())
            {
                SPGroup Group = web.SiteGroups[groupName];
                foreach (SPUser user in Group.Users)
                {
                    //Condition not working
                    if (user == null)
                    {
                      //empty
                    } else {
                      //not empty
                    }
                 }
            }
        }
Was it helpful?

Solution

try below code,

            using (SPSite site = new SPSite("http://sp/sites/test"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string groupName = "Home members";
                    SPGroup Group = web.SiteGroups[groupName];
                    int count = Group.Users.Count; // count will give the number of users in the group, using that we can check whether users are available in a group or not
                    if (count > 0)
                    {
                        //group has users
                    }
                    else
                    {
                        //group doesnt have users
                    }
                }
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top