[英]Remove runtime generated controls in C# winform
I have code that generates textboxes when the user right-clicks on a panel. 我有用于在用户右键单击面板时生成文本框的代码。 I need a way to allow the user to also remove/delete the textbox control that was created. 我需要一种方法来允许用户也删除/删除创建的文本框控件。 This code is how I create the textboxes during runtime: 这段代码是我在运行时创建文本框的方式:
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();
}
I found code to remove controls in another post, but it isn't working for what I need. 我发现代码删除了另一篇文章中的控件,但它不能满足我的需求。 That code is below, but it is designed to search and delete the control based on the name. 该代码如下,但它旨在根据名称搜索和删除控件。 What I'm hoping to be able to do is right-click on the textbox that was created, and have an option to delete it. 我希望能够做的是右键单击已创建的文本框,并可以选择删除它。 Any help would be appreciated. 任何帮助,将不胜感激。
// 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);
}
After trial and error and a lot of reading, I found out that menu items don't remove the Focus from its current container. 经过反复试验和大量阅读后,我发现菜单项不会将Focus从当前容器中删除。 So, I have created a menu and added a "delete" button. 所以,我创建了一个菜单并添加了一个“删除”按钮。 It works great. 它很棒。
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.