在C#中如下代码
var cbo = new ComboBox();
cbo.DropDownStyle = ComboBoxStyle.DropDownList;
var cbo.DataSource = new int[]{1, 2, 3};
cbo.SelectedIndex = 0;
cbo.SelectedIndex = 1;
cbo.SelectedIndex 仍然等于 -1
并不会变成 1
甚至有可能抛出ArgumentOutOfRange异常
ComboBox 的 SelectedIndexChanged 等Event也不会被触发
直到ComboBox被Add到父控件或者Form之后,相关设置才有效。
更改代码为如下,可以解决:
var cbo = new ComboBox();
cbo.DropDownStyle = ComboBoxStyle.DropDownList;
cbo.BindingContext = new BindingContext();
var cbo.DataSource = new int[]{1, 2, 3};
cbo.SelectedIndex = 0;
cbo.SelectedIndex = 1;
感谢钱伟强
Reference:
https://bytes.com/topic/c-sharp/answers/777129-combobox-setting-both-datasource-selectedindex