g t
g t

Reputation: 7463

How to set Z-order of a Control using WinForms

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!)

Upvotes: 43

Views: 104120

Answers (4)

In C Sharp

Control.SetValue(Panel.ZIndexProperty,0);

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

Upvotes: 0

gVista
gVista

Reputation: 11

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);
        }
    }

Upvotes: 1

Iain Ward
Iain Ward

Reputation: 9936

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);

Upvotes: 31

SLaks
SLaks

Reputation: 887867

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

Upvotes: 53

Related Questions