ComboBox.SelectedValue在窗体的构造方法中为null [英] ComboBox.SelectedValue is null in the Form's constructor

查看:36
本文介绍了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.

推荐答案

您可以致电

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.

阅读

Handle属性的值是Windows HWND .如果手柄有尚未创建,引用此属性将强制句柄待创建.

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.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆