41

I'm writing a custom TextBox that upon gaining focus changes its border style.

As adding a border causes the control to overlap with those neighbouring it, I temporarily bring the text box to the front of the dialog (using textBox.BringToFront()).

However, once editing is complete and focus is lost, I would like to send the control back to its original position in the Z-order.

Is this possible (preferably in a simple way!)

g t
  • 7,287
  • 7
  • 50
  • 85

4 Answers4

50

Call the GetChildIndex and SetChildIndex methods of the parent's Controls collection.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
30

There is no Z-order as there was in VB, but you can use the GetChildIndex and SetChildIndex methods to get and set their indexes manually.

Here there's an example of how to use it. You will probably need to keep a record of each controls index though so you can set it back to it when it's finished with.

Something like this is probably what you're after:

// Get the controls index
int zIndex = parentControl.Controls.GetChildIndex(textBox);
// Bring it to the front
textBox.BringToFront();
// Do something...
// Then send it back again
parentControl.Controls.SetChildIndex(textBox, zIndex);
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
  • 10
    Everything changes when you dynamically make controls (in)visible. Set 'textbox.Visible = true' and it will have index 0. It complete ignores the order from the document outline. This took me a while to figure :) – FrankyHollywood Sep 05 '16 at 07:04
  • Was trying to figure this out too. This comment helped me out. Thx – baron_bartek Mar 05 '18 at 13:33
1

When used with the FlowLayoutPanel this will move a control up or down

    /// <summary>
    /// When used with the FlowLayoutPanel this will move a control up or down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="UpDown"></param>
    private void C_On_Move(object sender, int UpDown)
    {
        //If UpDown = 1 Move UP, If UpDown = 0 Move DOWN
        Control c = (Control)sender;
        // Get the controls index
        int zIndex = _flowLayoutPanel1.Controls.GetChildIndex(c);
        if (UpDown==1 && zIndex > 0)
        {
            // Move up one
            _flowLayoutPanel1.Controls.SetChildIndex(c, zIndex - 1);
        }
        if (UpDown == 0 && zIndex < _flowLayoutPanel1.Controls.Count-1)
        {
            // Move down one
            _flowLayoutPanel1.Controls.SetChildIndex(c, zIndex + 1);
        }
    }
gVista
  • 11
  • 2
0

In C Sharp

Control.SetValue(Panel.ZIndexProperty,0);

Control is your control. 0 is index of ZIndex. 0 is default value.