etoisarobot
etoisarobot

Reputation: 7814

Removing a control from Windows Form and adjusting other controls to fit

I have a Windows Form App that I can add user controls to by clicking a button. I can also delete one control at a time by selecting it and clicking a delete button. All that works fine but if I add three controls and delete the second there is an gap between the two remaining controls on the form. I would like to have all the remaining controls move up to fill in the gap.

Like this:

//Add three controls and we have this:
Control1
Control2
Control3

//Delete Control2 and we now have this:
Control1

Control3

//What I would like is this:
Control1
Control3

Here is what I have tried but it isn't doing the job

private void btQuestionDelete_Click(object sender, EventArgs e)
{
    bool adjustMode = false;
    int height = 0;

    foreach (Control c in this.tpQuestions.Controls)
    {
        if (c is QuestionControl)
        {
            if (adjustMode)
            {
                int moveUpBy = c.Top - height;
                c.Top = moveUpBy;
                c.Parent.Refresh();
            }
            else
            {
                QuestionControl q = (QuestionControl)c;
                if (q.IsSelected)
                {
                    this.tpQuestions.Controls.Remove(c);
                    adjustMode = true;
                    height = q.Height;
                }
            }
        }
    }
}

Upvotes: 2

Views: 2226

Answers (2)

danyolgiax
danyolgiax

Reputation: 13116

To add a control just do this:

public void AddControl(ControlToAdd item)
{
    item.Dock = DockStyle.Top;

    this.Controls.Add(item);
}

To remove a control just Dispose it! All remaining controls will slide up!

Upvotes: 0

DarkSquirrel42
DarkSquirrel42

Reputation: 10287

maybe you want to have a look at flowLayoutPanels ?

Upvotes: 2

Related Questions