简体   繁体   English

Winforms删除单击控件

[英]Winforms remove controls on click

In my application I am generating some controls dynamically. 在我的应用程序中,我正在动态生成一些控件。 On telerik menu control when I click I want to remove those controls and add new controls. 在单击Telerik菜单控件时,我要删除这些控件并添加新控件。 I am using the following code. 我正在使用以下代码。 It is removing the controls but only one control per click. 它正在删除控件,但每次单击仅删除一个控件。 Why this code is not removing all the controls at one time? 为什么此代码不能一次删除所有控件?

private void radMenuItem3_Click(object sender, EventArgs e)
{
    foreach (Control ctrl in rpvRecord.Controls)
    {
        ctrl.Dispose();
    }
}

if you want to remove all controls at once you can just use Clear() method 如果您想一次删除所有控件,则可以使用Clear()方法

private void radMenuItem3_Click(object sender, EventArgs e)
{
   rvpRecord.Controls.Clear();
}

Probably need to remove the item from the collection, and, you might be altering your collection count as you go through the loop by doing a foreach. 可能需要从集合中删除该项目,并且在遍历循环时通过进行foreach可能会更改集合计数。 You might want to iterate from rpvRecord.Controls.Count - 1 to 0 with i-- like this: 您可能希望使用i从rpvRecord.Controls.Count-1迭代到0,如下所示:

private void radMenuItem3_Click(object sender, EventArgs e)
{
    for (var i = rpvRecord.Controls -1; i >= 0; i --)
    {
        ctrl = rpvRecord.Controls[i];
        rpvRecord.Controls.Remove(cntrl);
        ctrl.Dispose();
    }
}

The issue is that you are deleting the control out of the collection that you are iterating through, which causes a change in the collection and causes the loop to fail. 问题是您要从要迭代的集合中删除控件,这会导致集合中的更改并导致循环失败。 I would suggest using a different style of loop to accomplish this. 我建议使用其他样式的循环来完成此操作。 For example: 例如:

private void radMenuItem3_Click(object sender, EventArgs e)
{
    while (rpvRecord.Controls.Count > 0)
    {
        ctrl = rpvRecord.Controls[0];
        rpvRecord.Controls.Remove(ctrl);
        ctrl.Dispose();
    }
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM