dotnet / dotnet/winforms

ComboBox internal state not consistent when inserting at SelectedIndex and IsHandleCreated == false

Open
#6,689 3 comments 0 reactions 0 assignees View on GitHub
:books: documentation help wanted
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
1d 13m
Merged PRs (30d)
85

Description

* .NET Core Version: 6.0.101

* Have you experienced this same bug with .NET Framework?:
Yes

**Problem description:**

Add items to the `ComboBox` and select one:

``` C#
comboBox1.Items.Add("Item 1");
comboBox1.Items.Add("Item 2");
comboBox1.Items.Add("Item 3");

comboBox1.SelectedIndex = 1;
```

Now insert at the selected index: `comboBox1.Items.Insert(1, "Test");`

If the handle has been created:

- Item will be inserted into collection
- `SelectedIndex` will increment
- `SelectedItem` and `Text` remain consistent

If the handle has not been created:

- Item will be inserted into collection
- `SelectedIndex` will remain the same
- `SelectedItem` will be the newly inserted item
- `Text` will match the old `SelectedItem`

Issue discovered while adding events to `Items` collection (#6673)

**Expected behavior:**

- Internal state of control should remain consistent
- Behavior when handle has not yet been created should match that of when it has been

**Minimal repro:**

- Create new WinForms project
- Add the following to `Main` just after `ApplicationConfiguration.Initialize();`

``` C#
var comboBox = new ComboBox();

comboBox.Items.Add("Item 1");
comboBox.Items.Add("Item 2");
comboBox.Items.Add("Item 3");
comboBox.SelectedIndex = 1;

comboBox.Items.Insert(1, "Test");
```

- Set a breakpoint on `comboBox.Items.Insert(1, "Test");`
- Observe the values of `SelectedIndex`, `SelectedItem` and `Text` before and after that line executes

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.