如何通过双击事件修改动态创建的Label控件文本?
实现Label双击重命名功能
步骤1:完善动态Label创建代码
原代码缺少将Label添加到窗体控件集合的逻辑,同时需要绑定双击事件,修改后的代码如下:
for (int j = 0; j < Nitelik_Counter; j++) { Label labeltest = new Label(); labeltest.Text = "N - " + j.ToString(); labeltest.TextAlign = ContentAlignment.MiddleCenter; labeltest.Location = new Point(10 + j * 70, 10); labeltest.Size = new Size(60, 20); // 固定大小,保证TextBox匹配 labeltest.MouseDoubleClick += Label_MouseDoubleClick; // 绑定双击事件 this.Controls.Add(labeltest); // 将Label添加到窗体 }
步骤2:实现Label双击事件,生成临时重命名输入框
双击Label时,创建一个与Label位置、大小完全匹配的TextBox,隐藏原Label并让TextBox获得焦点:
private void Label_MouseDoubleClick(object sender, MouseEventArgs e) { Label targetLabel = sender as Label; if (targetLabel == null) return; TextBox renameBox = new TextBox(); renameBox.Location = targetLabel.Location; renameBox.Size = targetLabel.Size; renameBox.Text = targetLabel.Text; renameBox.SelectAll(); // 选中全部文本,方便直接编辑 renameBox.Tag = targetLabel; // 关联原Label,后续查找更可靠 renameBox.KeyDown += RenameBox_KeyDown; renameBox.LostFocus += RenameBox_LostFocus; targetLabel.Visible = false; this.Controls.Add(renameBox); renameBox.Focus(); }
步骤3:实现重命名完成逻辑
通过回车事件或失去焦点事件触发重命名保存,将TextBox的文本同步到Label,并清理临时控件:
private void RenameBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { CompleteRename(sender as TextBox); } } private void RenameBox_LostFocus(object sender, EventArgs e) { CompleteRename(sender as TextBox); } private void CompleteRename(TextBox renameBox) { if (renameBox == null) return; Label targetLabel = renameBox.Tag as Label; if (targetLabel != null) { targetLabel.Text = renameBox.Text; targetLabel.Visible = true; } this.Controls.Remove(renameBox); renameBox.Dispose(); }
内容的提问来源于stack exchange,提问作者Sultan Çepni
相关产品推荐
相关产品推荐

