ComboBox.SelectedValue is null in the Form's constructor

谁说我不能喝 提交于 2021-02-04 08:01:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!