![](/img/trans.png)
[英]How to add value to ComboBox's items, so I can choose it like this comboBox.SelectedIndex = myInt?
[英]How do I wait for a handle to be created for a comboBox, so that I can change the selectedIndex?
我用ComboBox
解决这个问题。
我需要以编程方式创建它,设置一个DataSource
,将其添加到我的表单中,然后更改SelectedIndex
。 我正在这样做:
rectangle = new Rectangle(x, y, width, height)
ComboBox cb = new ComboBox
{
Size = Rectangle.Size,
Location = Rectangle.Location,
DataSource = new List<string>(comboBoxDataSource),
};
Form1.Controls.Add(cb);
cb.SelectedIndex = index;
当程序到达最后一行时,我抛出一个错误,说:
System.ArgumentOutOfRangeException:'InvalidArgument =值'4'对于'SelectedIndex'无效。 参数名称:SelectedIndex'
当代码崩溃时,我可以看到ComboBox
包含6个项目,因此索引'4'在这一点上是否有效?
我已经阅读了一些有关此问题的文章和其他问题,但没有发现有任何效果。 我认为这是因为在尝试更改索引之前,该表单没有为ComboBox
创建句柄。
有没有人遇到过类似的问题或知道解决方案?
将组合框添加到控件后,绑定数据源。 然后您可以选择一个项目。
var dataSource = new List<string> { "one", "two", "three", "four", "five" };
var rectangle = new Rectangle(10, 10, 100, 40);
ComboBox cb = new ComboBox
{
Location = rectangle.Location,
Size = rectangle.Size,
};
this.Controls.Add(cb);
cb.DataSource = new List<string>(dataSource);
cb.SelectedIndex = 3;
添加一个BindingSource
并设置其DataSource
。 将绑定上下文添加到组合框,然后将组合框DataSource
设置为BindingSource.DataSource
。 见下文:
string[] dataSource = new string[30];
for (int i = 0; i < 30; i++) {
dataSource[i] = "test " + i.ToString();
}
ComboBox cb = new ComboBox();
cb.Size = new Size(121, 21);
cb.Location = new Point(55, 74);
BindingSource bS = new BindingSource();
cb.BindingContext = new BindingContext();
bS.DataSource = dataSource;
cb.DataSource = bS.DataSource;
cb.SelectedIndex = 4; // shoul and does display test 3
this.Controls.Add(cb);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.