0

i want to check in my code if the registered user be in a specific group . When i use IsCurrentUserMemberOfGroup like this :

SPUser e = SPContext.Current.Web.CurrentUser;
using (SPSite userContextSite = new SPSite("Web URL", e.UserToken))
{
    using (SPWeb userContextWeb = userContextSite.OpenWeb())
    {
        if(userContextWeb.IsCurrentUserMemberOfGroup(SPContext.Current.Web.SiteGroups["Dammak Hayah Members"].ID))
    }
}

error : Group cannot be found.

2

SharePoint seems to throw a “Group not found” error if the user is not a member of the group.

Hence use the try-catch:

private bool IsMemberOf(string groupName)
{
    SPUser user = SPContext.Current.Web.CurrentUser;

    try
    {
        if (user.Groups[groupName] != null)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}

Call as:

IsMemberOf("group name here");

Reference: http://chris.gg/2010/02/how-to-check-whether-a-sharepoint-user-is-in-a-particular-group/

OR You can try this code:

private bool IsMemberOf(string groupName)
{
SPUser user = SPContext.Current.Web.CurrentUser;
SPGroup group = SPContext.Current.Web.Groups[groupName];

return group.Users.GetCollection(new string[] { user.LoginName }).Count > 0;

}
  • i tried this but i think i have a problem with group name SPGroup group = web.SiteGroups["Dammak Hayah Owners"]; – user24424 Apr 26 '14 at 6:01
  • i got the group name from : site settings-->people and groups --> and take the name of group from the left side – user24424 Apr 26 '14 at 6:15
  • is the user member of this group? SharePoint seems to throw a “Group not found” error if the user is not a member of the group. – variable Apr 26 '14 at 6:22
  • yes the user is member in group – user24424 Apr 26 '14 at 6:30
1
SPWeb site = SPContext.Current.Web;
SPGroup Groupname = site.Groups["your group name"];
bool isexist = site.IsCurrentUserMemberOfGroup(Groupname);
  • i do this but the same error group cannot be found – user24424 Apr 26 '14 at 5:23
  • i think i have problem with group name .. please tell me from where take the group name and thank you for help – user24424 Apr 26 '14 at 5:25
  • have you tried with other group names? – SharePointMan Apr 26 '14 at 5:33
  • yes tried with other group – user24424 Apr 26 '14 at 5:56
  • its working for other groups? – SharePointMan Apr 26 '14 at 6:21
0

This code will help you

SPUser User = oWeb.EnsureUser(LoginName);
var spGroup = oWeb.Groups[GroupName];    
isResult = oWeb.IsCurrentUserMemberOfGroup(spGroup.ID);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.