Controls in the same DataGridView column dont rend

2019-02-15 13:33发布

问题:

GOOD                                                  BAD

I'm hosting different controls in DataGridView column. When I add controls at the same time I initialize the grid the controls show as Textboxes (BAD). If I add the controls after the DataGridView has been initialized controls render correctly (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;
}

How does one make the controls render correctly during initialization?

(I'm adding DataGridViews dynamically).

UPDATE: Jacob Seleznev's answer works for Forms but not user controls which is what I need... Here is how to reproduce it:

In the Form:

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

The user Control:

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
    }

}

回答1:

This worked for me:

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