ComboBox.SelectedValue 在 Form 的构造函数中为 null [英] ComboBox.SelectedValue is null in the Form's constructor

查看:28
本文介绍了ComboBox.SelectedValue 在 Form 的构造函数中为 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 时,SelectedValuenull.

When I set the value cmb.SelectedValue, SelectedValue is null.

我知道如果我将此代码移动到 Form1_Load 处理程序,它将按预期工作,但我需要在 Form 的构造函数中使用它.

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.

推荐答案

您可以调用 CreateControl() 在窗体的构造函数中强制创建控件的句柄.

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:

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

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