本文介绍了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.
推荐答案
您可以致电 CreateControl()在窗体的构造函数中强制创建控件的句柄.
You can call CreateControl() in the Form's Constructor to force the creation of the control's handle.
阅读句柄属性:
SelectValue
属性在此之后将具有值.
The SelectValue
property will have value after this point.
public Form1()
{
InitializeComponent();
// [...]
this.Controls.Add(cmb);
cmb.CreateControl();
cmb.SelectedValue = 2;
}
这篇关于ComboBox.SelectedValue在窗体的构造方法中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!