[英]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.