08 October 2009

C# : Dynamically adding control with docking works in reverse way

To create the list of labels (like the following image) dynamically, firstly I wrote the code below the image (very much expected).

for (int i = 0; i < 5; i++)
{
Label l = new Label();
l.Text = "Label" + (i + 1);
l.Dock = DockStyle.Top;
panel1.Controls.Add(l);
}


Surprisingly, I discovered that it is working just in reverse way of my expectation! (like below)


The fact is the first control is being drawn at the bottom. So, I solved it with the help of Controls.SetChildIndex() function in the following way.

Solution:

for (int i = 0; i < 5; i++)
{
Label l = new Label();
l.Text =
"Label" + (i + 1);
l.Dock =
DockStyle.Top;
panel1.Controls.Add(l);
panel1.Controls.SetChildIndex(l, 0);
}

Improved Solution:

In the given solution, what actually happens is that the new control is added at the top (for the style Dock.Top), then it is moved to the bottom. But this change in position may cause unwanted blinking of UI. To avoid this unwanted situation, follow the following steps

  • Add the new control with size (0,0)
  • Change its index to 0 (upper solution)
  • Resize again the control to actual size
Code:

for (int i = 0; i < 5; i++)
{
Label l = new Label();
l.Text = "Label" + (i + 1);
l.Dock = DockStyle.Top;
addControlInContainer(panel1, l);
}


public static void addControlInContainer(Control container, Control control)
{
// save actual size
Size tempSize = control.Size;

// Add the new control with size (0,0)
control.Size = new Size(0, 0);
container.Controls.Add(control);

// Change its index to 0
container.Controls.SetChildIndex(control, 0);

// Resize the control to actual size
control.Size = tempSize;
}



0 Comments:

 

© 2007 t!ps n tr!cks: C# : Dynamically adding control with docking works in reverse way



Template unik dari rohman


---[[ Skip to top ]]---