好坏
![enter image description here](https://i.stack.imgur.com/ifrKA.png)
我在 DataGridView 列中托管不同的控件。当我在初始化网格的同时添加控件时,控件显示为文本框(不好)。如果我在 DataGridView 初始化后添加控件,控件会正确呈现(好)。
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:Jacob Seleznev 的答案适用于表单,但不适用于我需要的用户控件......以下是重现它的方法:
在表格中:
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
}
}