点击按钮加载多GroupBox后,旧TextBox的KeyDown事件失效解决方案咨询
问题解决:保留动态加载GroupBox中控件的事件有效性
问题根源
你的代码里Tb1、Tb2这些TextBox变量是类级别的字段,每次创建新GroupBox时,这些变量都会被新生成的TextBox覆盖。而事件处理方法里如果直接用Tb1.Text这类代码,实际拿到的是最后一次创建的TextBox的内容,不是当前触发事件的那个控件,所以看起来旧GroupBox的事件“失效”了——其实事件本身绑定是正常的,只是你用错了控件实例。
修复步骤
- 把
Tb1`Tb4`、`lbl1`lbl4、groupBox改成GetGroupBox方法内的局部变量,不要用类字段存储。 - 在事件处理方法里,通过
sender参数获取当前触发事件的TextBox,再获取它的文本内容。
修改后的完整代码
int count; private GroupBox GetGroupBox(int a) { // 改为局部变量 GroupBox groupBox = new GroupBox() { Text = "S" + a.ToString(), Name = "S" + a.ToString(), Width = 150, Height = 150, Location = new Point(15 + (count - 1) * (150 + 5), 270) }; for (int i = 0; i < 5; i++) { switch (i) { case 1: // Add a TextBox and A Label // 改为局部变量 TextBox tb1 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 30) }; groupBox.Controls.Add(tb1); tb1.KeyDown += Tb1_KeyDown; Label lbl1 = new Label() { Name = "lbl1", Text = "r1.X", Width = 40, Height = 15, Location = new Point(10, 30) }; groupBox.Controls.Add(lbl1); break; case 2: // Add a TextBox and A Label TextBox tb2 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 50) }; groupBox.Controls.Add(tb2); tb2.KeyDown += Tb2_KeyDown; Label lbl2 = new Label() { Name = "lbl2", Text = "r1.Y", Width = 40, Height = 15, Location = new Point(10, 50) }; groupBox.Controls.Add(lbl2); break; case 3: // Add a TextBox and A Label TextBox tb3 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 70) }; groupBox.Controls.Add(tb3); tb3.KeyDown += Tb3_KeyDown; Label lbl3 = new Label() { Name = "lbl3", Text = "r1.Width", Width = 50, Height = 15, Location = new Point(10, 70) }; groupBox.Controls.Add(lbl3); break; case 4: // Add a TextBox and A Label TextBox tb4 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 90) }; groupBox.Controls.Add(tb4); tb4.KeyDown += Tb4_KeyDown; Label lbl4 = new Label() { Name = "lbl4", Text = "r1.Height", Width = 50, Height = 15, Location = new Point(10, 90) }; groupBox.Controls.Add(lbl4); break; } } return groupBox; } private void Tb4_KeyDown(object sender, KeyEventArgs e) { // 通过sender获取当前触发事件的TextBox if(sender is TextBox currentTb) { // 使用currentTb.Text作为参数执行计算 string input = currentTb.Text; // 你的计算逻辑 } } private void Tb3_KeyDown(object sender, KeyEventArgs e) { if(sender is TextBox currentTb) { string input = currentTb.Text; // 你的计算逻辑 } } private void Tb2_KeyDown(object sender, KeyEventArgs e) { if(sender is TextBox currentTb) { string input = currentTb.Text; // 你的计算逻辑 } } private void Tb1_KeyDown(object sender, KeyEventArgs e) { if(sender is TextBox currentTb) { string input = currentTb.Text; // 你的计算逻辑 } } private void button1_Click(object sender, EventArgs e) { this.Controls.Add(GetGroupBox(++count)); }
额外优化建议
- 可以把四个TextBox的事件绑定到同一个处理方法,通过判断控件的关联标签或位置区分计算逻辑,减少重复代码。
- 如果需要后续访问某个GroupBox里的控件,可以把所有创建的GroupBox存入
List<GroupBox>集合,方便后续查找和操作。
内容的提问来源于stack exchange,提问作者Paras
相关产品推荐
相关产品推荐

