/// <summary> /// Handles the Click event of the lbPlaceInGroup control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbPlaceInGroup_Click( object sender, EventArgs e ) { var col = gGroupPlacements.Columns.OfType<GroupPickerField>().FirstOrDefault(); if ( col != null ) { var placements = new Dictionary<int, List<int>>(); var colIndex = gGroupPlacements.Columns.IndexOf( col ).ToString(); foreach ( GridViewRow row in gGroupPlacements.Rows ) { GroupPicker gp = row.FindControl( "groupPicker_" + colIndex.ToString() ) as GroupPicker; if ( gp != null ) { int? groupId = gp.SelectedValueAsInt(); if ( groupId.HasValue ) { int registrantId = (int)gGroupPlacements.DataKeys[row.RowIndex].Value; placements.AddOrIgnore( groupId.Value, new List<int>() ); placements[groupId.Value].Add( registrantId ); } } } using ( var rockContext = new RockContext() ) { var groupMemberService = new GroupMemberService( rockContext ); // Get all the registrants that were selected var registrantIds = placements.SelectMany( p => p.Value ).ToList(); var registrants = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias" ).AsNoTracking() .Where( r => registrantIds.Contains( r.Id ) ) .ToList(); // Get any groups that were selected var groupIds = placements.Keys.ToList(); foreach ( var group in new GroupService( rockContext ) .Queryable( "GroupType" ).AsNoTracking() .Where( g => groupIds.Contains( g.Id ) ) ) { foreach ( int registrantId in placements[group.Id] ) { int? roleId = group.GroupType.DefaultGroupRoleId; if ( !roleId.HasValue ) { roleId = group.GroupType.Roles .OrderBy( r => r.Order ) .Select( r => r.Id ) .FirstOrDefault(); } var registrant = registrants.FirstOrDefault( r => r.Id == registrantId ); if ( registrant != null && roleId.HasValue && roleId.Value > 0 ) { var groupMember = new GroupMember(); groupMember.PersonId = registrant.PersonAlias.PersonId; groupMember.GroupId = group.Id; groupMember.GroupRoleId = roleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMemberService.Add( groupMember ); } } } rockContext.SaveChanges(); } } BindGroupPlacementGrid(); }