C# 将数据附加到组合框中时,组合框所选索引将更改为0

C# 将数据附加到组合框中时,组合框所选索引将更改为0,c#,.net,C#,.net,嗨,我正在表单加载中使用以下代码 Combobox1.DataSource=GetItems(); 然后默认情况下选择第一项。您不是在追加数据,而是完全替换数据。因此,选定的索引将被重置。你可以记住它,然后像这样把它放回去 int oldIndex = Combobox1.SelectedIndex; Combobox1.DataSource= GetItems(); Combobox1.SelectedIndex = oldIndex; //should check to see if th

嗨,我正在表单加载中使用以下代码

Combobox1.DataSource=GetItems();

然后默认情况下选择第一项。

您不是在追加数据,而是完全替换数据。因此,选定的索引将被重置。你可以记住它,然后像这样把它放回去

int oldIndex = Combobox1.SelectedIndex;
Combobox1.DataSource= GetItems();
Combobox1.SelectedIndex = oldIndex; //should check to see if the new list is long enough.

我想您的组合框的DropDownStyle属性设置为DropDownList。如果是,设置数据源会自动将SelectedIndex设置为0(列表中的第一个元素)。你可以写:

Combobox1.DataSource=GetItems();
Combobox1.SelectedIndex = -1;