Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ public virtual void Add(Control? value)
// Add the control
InnerList.Add(value);

int _savedTabIndex = value._tabIndex;

if (value._tabIndex == -1)
{
// Find the next highest tab index
Expand Down Expand Up @@ -101,6 +103,25 @@ public virtual void Add(Control? value)
// you could end up with a control half reparented.
value.AssignParent(Owner);
}
catch
{
// AssignParent may throw for invalid parents, leaving the control partially added.
// Roll back the failed add to keep the collection and parent state consistent.
if (InnerList.Contains(value))
{
InnerList.Remove(value);
}

// AssignParent may have already changed the parent before throwing.
// Restore the previous parent to keep Parent and Controls collection in sync.
if (value._parent == Owner)
{
value._parent = oldParent;
}

value._tabIndex = _savedTabIndex;
throw;
}
finally
{
if (oldParent != value._parent && (Owner._state & States.Created) != 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,38 @@ public void ControlCollection_Ctor_NullOwner_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("owner", () => new Form.ControlCollection(null));
}

[WinFormsFact]
public void ControlCollection_Add_InvalidTabPageParent_DoesNotLeaveHalfAddedControl()
{
using Form form = new();
using TabPage tabPage = new();

int oldCount = form.Controls.Count;

Assert.ThrowsAny<Exception>(() => form.Controls.Add(tabPage));

Assert.Equal(oldCount, form.Controls.Count);
Assert.False(form.Controls.Contains(tabPage));
Assert.Null(tabPage.Parent);
}

[WinFormsFact]
public void ControlCollection_Clear_AfterFailedTabPageAdd_DoesNotHang()
{
using Form form = new();
using Button button = new() { Name = "button1" };
using TabPage tabPage = new();

form.Controls.Add(button);

Assert.ThrowsAny<Exception>(() => form.Controls.Add(tabPage));

// If the failed add left the TabPage half-added,
// Clear() could hang. After the fix, it should complete normally.
form.Controls.Clear();

Assert.Empty(form.Controls);
Assert.Null(tabPage.Parent);
}
}
Loading