在同一列的DataGridView控件不呈现在初始化网格(Controls in the same

2019-07-21 01:28发布

好坏

我在DataGridView中列托管不同的控件。 当我在同一时间添加控件初始化我网格控件显示为文本框(BAD)。 如果我的控件添加在DataGridView已初始化后控件呈现正常(GOOD)。

public Form1()
{
        InitializeComponent();
        ControlsInGridViewColumn(); //<- renders controls as textboxes
}

private void button1_Click(object sender, EventArgs e)
{
        ControlsInGridViewColumn();  //<- does correctly render controls
}

private void ControlsInGridViewColumn()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("name");
    for (int j = 0; j < 10; j++)
    {
        dt.Rows.Add("");
    }
    this.dataGridView1.DataSource = dt;
    this.dataGridView1.Columns[0].Width = 200;

    DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();
    ComboBoxCell.Items.AddRange(new string[] { "aaa","bbb","ccc" });
    this.dataGridView1[0, 0] = ComboBoxCell;
    this.dataGridView1[0, 0].Value = "bbb";

    DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell();
    this.dataGridView1[0, 1] = TextBoxCell;
    this.dataGridView1[0, 1].Value = "some text";

    DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell();
    CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    this.dataGridView1[0, 2] = CheckBoxCell;
    this.dataGridView1[0, 2].Value = true;
}

怎样才能使控件初始化过程中正确呈现?

(我在动态添加DataGridViews)。

UPDATE:雅各谢列兹尼奥夫的答案适用于形式,但不是用户控件这正是我需要的...这里是如何重现它:

形式:

private void button3_Click(object sender, EventArgs e)
{
    this.Controls.Add(new userCtrl());
}

用户控制:

public partial class userCtrl : UserControl
{
    public userCtrl()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        ControlsInGridViewColumn();
        base.OnLoad(e);
    }

    public void ControlsInGridViewColumn()
    {
        //same code as above
    }

}

Answer 1:

这为我工作:

    protected override void OnLoad(EventArgs e)
    {
        ControlsInGridViewColumn();  //<- does correctly render controls
        base.OnLoad(e);
    }


文章来源: Controls in the same DataGridView column dont render while initializing grid