如何在C#中删除一个控件

2025-03-01 06:36:39
推荐回答(4个)
回答1:

看CheckBox的parent是谁

1、如果CheckBox是放在Panel(比如Canvas, Grid, DockPanel之类的)中的,调用 xxx.Children.Remove(checkBox1);

2、如果是放在ContentControl(例如Button)或者HeaderedContentControl(例如TabItem)的,调用
xxx.Content = null

3、如果是直接放在ItemsControl(例如ListBox)或者HeaderedItemsControl(例如TreeViewItem)中的,调用
xxx.Items.Remove(checkBox1);

如果不是直接放的,是通过数据绑定+模板生成的,直接删除对应的数据。

回答2:

貌似不可以删除控件代码吧。你可以试试把他隐藏掉。

回答3:

为何非得删除,隐藏不行么。共同等待高手前来。

回答4:

参考思路:
遍历后,然后进行删除;
参考代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Queue query = new Queue();//临时存储获取到的control控件
///


/// 递归获取panel1上的所有控件,并临时存储到一个队列中
///

///
void DS(Control item)
{
for (int i = 0; i < item.Controls.Count;i++ )
{
if (item.Controls[i].HasChildren)
{
DS(item.Controls[i]);
}
else
{
query.Enqueue(item.Controls[i]);
}

}

}
private void button1_Click(object sender, EventArgs e)
{
DS(panel1);
//删除遍历到的控件
while (query.Count != 0)
{
query.Dequeue().Dispose();
}
}
}
}