Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - Adding / removing controls with same reference name

I am adding controls on a panel one after the other when the user clicks on a button. The controls are displayed one after the other on the panel. When the panel is full e.g. ten, the next control added has to replace the first control that was added, but first I need to remove the first control.... the problem is that all the controls that are being created have the same reference e.g. "pic", now when I use panel1.Controls.Remove(pic) it does not specify that the control at the first position needs to be removed!!

int index = 0;  

if (util.GetSize() != 10)
{
    ms.Controls.Add(musNote);
}
else
{   
    ms.Controls.Add(musNote); //this to replace first musNote added... but before I need to remove the musNote that in that position already (problem all of the are musNote!!
    index++;
    if (index == 10)
    {
        index = 0;
    }
}
musNote.ShowNote();

The above is not the entire code but should be enough to tackle the problem.. if any info. is needed please ask me np. Tks in advance for the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you just want to remove the first child use RemoveAt method

myPanel.Controls.RemoveAt(0);

Don't use above code, it will leak in Handle, use Dispose as @Hans suggested in comments

myPanel.Controls[0].Dispose();//This takes care of destroying the window

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...