Controls in the same DataGridView column dont render while initializing grid

我与影子孤独终老i 提交于 2019-11-30 18:51:16

问题


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


来源:https://stackoverflow.com/questions/15238322/controls-in-the-same-datagridview-column-dont-render-while-initializing-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!