当控件添加到 Windows 窗体中的 TableLayoutPanel 时,我需要采取措施。我正在处理控件的 ParentChanged 事件以查明控件是否已添加到父级(此处为 TableLayoutPanel),但我收到的索引是-1。
TableLayoutPanel t;
private void button1_Click(object sender, EventArgs e)
{
// this.Text = tableLayoutPanel1.Height.ToString();
t = new TableLayoutPanel();
t.Dock = DockStyle.Fill;
//t.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
t.AutoSize = true;
//t.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
t.RowStyles.Add(new RowStyle(SizeType.AutoSize));
t.RowStyles.Add(new RowStyle(SizeType.AutoSize));
t.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
t.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
panel1.Controls.Add(t);
t.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
Label lbl = new Label();
lbl.ParentChanged += new EventHandler(lbl_ParentChanged);
lbl.Margin = new System.Windows.Forms.Padding(20, 150, 20, 20);
lbl.Text = "Hello";
t.Controls.Add(lbl, 0, 0);
}
void lbl_ParentChanged(object sender, EventArgs e)
{
Label lbl = (Label)sender;
int row = t.GetRow(lbl);//here I get row = -1 ??????
}
我需要添加控件的行号。控件应采取独立于何时添加到 TableLayoutPanel 的操作。如何得到它?
void t_ControlAdded(object sender, ControlEventArgs e)
{
int row = t.GetRow(e.Control); //this also gives row = -1
}