I am trying to add users to a group through people picker. When i run it, SPgroup returns null and it throws an error saying group cannot be found. I have tried with both SPweb context and SPsite with and without SPsecurity. New developer, thanks for any advice.
public void Button6_Click(object sender, EventArgs e){
if (PeopleEditor1.Accounts.Count > 0)
{
PickerEntity pe = (PickerEntity)PeopleEditor1.Entities[0];
string username = pe.Description;
string group = DropDownList2.SelectedItem.Text;
addUserToGroup(group, username);
}
else
{
Label3.Text = "Please insert and validate a user in people picker.";
PeopleEditor1.SetFocus();
}
}
public void addUserToGroup(string groupName, string userLoginName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(Page.Request.Url.ToString());
SPWeb web = site.OpenWeb();
// SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
SPUser spUser = web.EnsureUser(userLoginName);
SPGroup spGroup = web.Groups[groupName];
if (spUser != null && spGroup != null)
{
spGroup.AddUser(spUser);
}