Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

c# - ComboBox.SelectedValue is null in the Form's constructor

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...