Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态组合框数据源表单加载_C#_Vb.net_Winforms_Combobox - Fatal编程技术网

C# 动态组合框数据源表单加载

C# 动态组合框数据源表单加载,c#,vb.net,winforms,combobox,C#,Vb.net,Winforms,Combobox,我正在创建一个动态组合框并添加到表单中。我试图用ArrayList中的数据源填充组合框,然后根据属性中的值在组合框中选择一项 问题是,只有在表单加载事件完成并且表单可见之后,组合框项才会被绑定。因此,当我试图设置组合框的选定索引时,组合框是空的。请参阅代码了解我的详细操作,并参考代码中的注释: Dim cboValues As New ComboBox cboValues.Width = fieldControlWidth cboValues.DropDownStyle = ComboBoxSt

我正在创建一个动态组合框并添加到表单中。我试图用ArrayList中的数据源填充组合框,然后根据属性中的值在组合框中选择一项

问题是,只有在表单加载事件完成并且表单可见之后,组合框项才会被绑定。因此,当我试图设置组合框的选定索引时,组合框是空的。请参阅代码了解我的详细操作,并参考代码中的注释:

Dim cboValues As New ComboBox
cboValues.Width = fieldControlWidth
cboValues.DropDownStyle = ComboBoxStyle.DropDownList

cboValues.Name = "cboResult"

For Each d As SystemTaskResult In [Enum].GetValues(GetType(SystemTaskResult))
    Dim cv As New ComboBoxDisplayValue(d.ToString, d)
    arrValues.Add(cv)
Next

cboValues.DataSource = arrValues
cboValues.DisplayMember = "Display"
cboValues.ValueMember = "Value"

Dim val As SystemTaskResult = DirectCast(p.GetValue(Me.Task, Nothing), SystemTaskResult)

'Was trying to get this to work, but commented out to try the below
'cboValues.SelectedIndex = cboValues.Items.IndexOf(New ComboBoxDisplayValue(val.ToString, val))

'Then this doesn't work because the combo box hasn't updated it's DataSource yet, which is probably the reason for the above not working as well.
For i = 0 To cboValues.Items.Count - 1
    cboValues.SelectedIndex = i
    If cboValues.SelectedValue = val Then
        Exit For
    End If
Next

holdPanel.Controls.Add(cboValues)
如何为组合框选择正确的索引,而不使用黑客加载计时器或诸如此类的蠢事?

试试看。见:


感谢您的回答,但组合框项目在表单中仍然为0。显示事件。请记住,这是一个动态控件,而不是窗体上已有的控件。我认为这是这里的问题。@ScottN不确定您为什么坚持在同一个函数中执行这些操作,但您也可以尝试在显示的事件中创建ComboBox抱歉,如果我在窗体加载中创建控件,然后在显示的窗体中尝试将ComboBox设置为正确的选定索引,则现在将填充项,我希望在同样的功能中实现这一点。我想不可能。我知道这是一个老问题,但我也有同样的问题,我通过循环列表解决了它,然后使用Combobox1.Items.add添加每个项目