ComboBox.SelectedValue在窗体的构造方法中为null [英] ComboBox.SelectedValue is null in the Form's constructor
本文介绍了ComboBox.SelectedValue在窗体的构造方法中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我生成了一个非常简单的代码段:
I generated a very simple code snippet:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Rows.Add(1, "One");
dt.Rows.Add(2, "Two");
cmb = new ComboBox();
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DisplayMember = "Title";
cmb.ValueMember = "ID";
cmb.DataSource = dt;
this.Controls.Add(cmb);
cmb.SelectedValue = 2;
}
}
当我将值设置为 cmb.SelectedValue
时, SelectedValue
为 null
.
When I set the value cmb.SelectedValue
, SelectedValue
is null
.
我知道,如果我将此代码移到 Form1_Load
处理程序中,它将按预期工作,但是我需要在Form的Constructor中使用它.
I know that if I move this code to the Form1_Load
handler, it will work as expected, but I need it in Form's Constructor.
推荐答案
You can call CreateControl() in the Form's Constructor to force the creation of the control's handle.
强制创建可见控件,包括创建手柄和任何可见的子控件.
Forces the creation of the visible control, including the creation of the handle and any visible child controls.
查看全文