问题
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;
}
}
When I set the value cmb.SelectedValue
, SelectedValue
is null
.
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.
回答1:
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.
The same effect can be achieved reading the Handle property:
The value of the Handle property is a Windows
HWND
. If the handle has not yet been created, referencing this property will force the handle to be created.
The SelectValue
property will have value after this point.
public Form1()
{
InitializeComponent();
// [...]
this.Controls.Add(cmb);
cmb.CreateControl();
cmb.SelectedValue = 2;
}
回答2:
Please try this instead:
.
.
.
this.Controls.Add(cmb);
cmb.VisibleChanged += VisibleChangedHandler;
void VisibleChangedHandler(object sender, EventArgs e)
{
cmb.SelectedValue = 2;
cmb.VisibleChanged -= VisibleChangedHandler;
}
The .NET Framework won't let you set the SelectedIndex
or SelectedValue
for a ComboBox control until that control is visible. So if you must do this in the Form constructor, you'll need to defer the "Selected" assignment until such time that the cmb control becomes visible. To do that, hook its VisibleChanged event by wiring up a handler. Here I've added a VisibleChangedHandler as a local function (you can make it regular method by moving it out of the Load method, but it makes sense to keep it local since you're going to be using it only once). Add the handler--then remove the handler once it's been executed.
来源:https://stackoverflow.com/questions/62381280/combobox-selectedvalue-is-null-in-the-forms-constructor