Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
550 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...