ArgumentException: Getting control 4's position in a group with only 4 controls

Hey guys, could someone help me out with solving this error? I am basically trying to move gui components to a different line when the edge of the editor window is reached. But I get this error at the line 15. where BeginHorizontal is. Anyone can help?

    EditorGUILayout.BeginHorizontal();
            for (int i= 0; i < theNames.Count; i++) {
     
                    string name = theNames[i];
     
                    GUILayout.Space(-6);
                    GUILayout.Box(name, GUILayout.Width(80), GUILayout.Height(20));
     
                    rect = GUILayoutUtility.GetLastRect ();
     
                    //Check if the Box GUI right edge has passed the current width of the window
                    if(rect.xMax > window.position.width){
                            //End current line and begin a new one
                            EditorGUILayout.EndHorizontal();
                            EditorGUILayout.BeginHorizontal();
                                                           
                    }
     
            }
    EditorGUILayout.EndHorizontal();

Thanks.

Can’t selection grid solve your problem ?

GUILayout.SelectionGrid(-1, theNames, 10, GUI.skin.box, GUILayout.Width(window.position.width));