I need to take an action when a control is added to a TableLayoutPanel in Windows Forms. I am handling ParentChanged event of the control to find out if the control is added to a parent(here TableLayoutPanel), but the index I receive is -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 ??????
}
I need row number to which the control is added. The control should take action independent of when it is added to the TableLayoutPanel. How to get it ?
void t_ControlAdded(object sender, ControlEventArgs e)
{
int row = t.GetRow(e.Control); //this also gives row = -1
}
Try do your button1_Click stuff after you have left the message (windows messagequeue message):
You need to increment
RowCount/ColumnCount
, if you add newRowStyles/ColumnStyles
to yourTableLayoutPanel
. After this you can easily use theGetPositionFromControl(Control value)
Method.I think,
ControlAdded
Event is the better approach in this case. Give it a try.Do it like this:
From the msdn page:
Use the following: