Reputation: 1781
Note : In WinForm
I facing problem in TableLayoutPanel. I adding and removing the control dynamicall using TableLauoutPanel. My problem is, if i remove the control in the middle (ie i added TextBox1, TextBox2 and TextBox3 and now i removed TextBox2) at this time other controls are not resized properlly. When the last control (ie TextBox3 ) is removed, its resizing properlly. I attached my code here. What is the problem?
///HERE tbl is the TableLayoutPanel
private void AddText_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.MouseDoubleClick += new MouseEventHandler(txt_MouseDoubleClick);
txt.Multiline = true;
txt.Dock = DockStyle.Fill; NEWADD(txt);
}
private void NEWADD(Control ctrl)
{
tbl.RowCount += 1;
tbl.RowStyles.Add(new RowStyle(SizeType.Percent, 100F / tbl.RowStyles.Count));
tbl.Controls.Add(ctrl, 0, tbl.RowStyles.Count - 1);
foreach (RowStyle row in tbl.RowStyles)
{
row.SizeType = SizeType.Percent;
row.Height = 100F / (tbl.RowStyles.Count);
}
}
private void RemoveControl(Control ctrl)
{
tbl.RowCount -= 1;
tbl.Controls.Remove(ctrl);
tbl.RowStyles.Clear();
for (int i = 0; i < tbl.Controls.Count; i++)
{
tbl.RowStyles.Add(new RowStyle(SizeType.Percent, 100F /( tbl.RowStyles.Count +1)));
}
foreach (RowStyle row in tbl.RowStyles)
{
row.SizeType = SizeType.Percent;
row.Height = 100F / (tbl.RowStyles.Count);
}
tbl.Refresh();
}
void txt_MouseDoubleClick(object sender, MouseEventArgs e)
{
RemoveControl(sender as Control);
}
Upvotes: 1
Views: 320
Reputation: 245389
Can't test it at the moment, but it looks like your problem is the logic for removing the row that the control is in.
tbl.RowCount -= 1
is always going to remove the last row. You need to move through each control that is in a row after the the you want to remove and shift your controls up one row. Maybe something like this...
foreach(Control control in tbl.Controls)
{
if(control.Row > controlToRemove.Row)
control.Row--;
}
Upvotes: 1
Reputation: 415600
Since it looks like you're also trying to dynamically create a new table row for each control, you might do a little better with a FlowLayoutPanel. You should be able to style it to get a similar effect and it will be able to handle "row creation" automatically.
Upvotes: 0