开发者

Removing user controls from parent form

I use this code to show user control on main form

    private void MainForm_Load(object sender, EventArgs e)
    {
        Sell sell = ne开发者_开发百科w Sell();
        sell.Dock = DockStyle.Fill;
        this.Controls.Add(sell);
    }

I want to remove this user control from main form but this code does not working

this.Controls.Remove(sell);

I tried this.Parent.controls.Remove(sell); but it does not work either. Please advise something...


Maybe you're creating another Sell control and trying to remove that? If so, that won't work because that's a different object from the one you added on form load.

One way to do what you want would be to give a name to your Sell control and use that name to remove it later:

private void MainForm_Load(object sender, EventArgs e)
{
    Sell sell = new Sell();
    sell.Name = "mainSell";
    sell.Dock = DockStyle.Fill;
    this.Controls.Add(sell);
}

// Later...
this.Controls.RemoveByKey("mainSell");


You defined sell control in MainForm_Load scope and want to remove it in another scope so you can't, you can define it in more general scope and then remove it:

Sell sell = new Sell();
private void MainForm_Load(object sender, EventArgs e)
{
    sell.Dock = DockStyle.Fill;
    this.Controls.Add(sell);
}

// other scope
this.Controls.Remove(sell);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜