[英]Remove runtime generated controls in C# winform
我有用于在用户右键单击面板时生成文本框的代码。 我需要一种方法来允许用户也删除/删除创建的文本框控件。 这段代码是我在运行时创建文本框的方式:
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Point cp = panel1.PointToClient(Cursor.Position);
i++;
TextBox text = new TextBox();
text = new TextBox();
text.Name = "user_textbox" + i.ToString();
text.Size = new System.Drawing.Size(panel1l.Width, 30);
text.Location = new Point(0, cp.Y); // puts box at current mouse position
panel1.Controls.Add(text);
text.Focus();
}
我发现代码删除了另一篇文章中的控件,但它不能满足我的需求。 该代码如下,但它旨在根据名称搜索和删除控件。 我希望能够做的是右键单击已创建的文本框,并可以选择删除它。 任何帮助,将不胜感激。
// this is code to remove controls using
// name of the control
foreach (Control ctrl in this.Controls)
{
if (ctrl.Name == "Textbox2")
this.Controls.Remove(ctrl);
}
经过反复试验和大量阅读后,我发现菜单项不会将Focus从当前容器中删除。 所以,我创建了一个菜单并添加了一个“删除”按钮。 它很棒。
private void deleteCurrentScheduleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ActiveControl is TextBox)
{
this.panel1.Controls.Remove(ActiveControl);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.