我在表单中有一个按钮。每次单击按钮时都会加载一个组框(您可以参考我之前的问题)。每个组框中有几个文本框和标签。我为组框中的文本框引发了keydown事件。keydown事件执行一些数学计算。
当只加载一个组框时,该按钮工作正常。但是,当加载第二个组框时,引发的事件对以前加载的组框中的文本框不起作用。它只对新的组框起作用。例如,如果在加载groupbox1后单击该按钮,则在第二次加载groupbox2时单击该按钮,等等...问题是keydown事件只对新加载的groupbox起作用。(即如果第三次点击按钮则keydown事件仅对组框3起作用。对于组框1和组框2,它不起作用)加载新的分组框时,应该如何保留前一个分组框中控件的事件。
我是这么试的:但问题依然存在。
int count;
private GroupBox GetGroupBox(int a)
{
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
Tb1 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 30) };
groupBox.Controls.Add(Tb1);
Tb1.KeyDown += Tb1_KeyDown;
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
Tb2 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 50) };
groupBox.Controls.Add(Tb2);
Tb2.KeyDown += Tb2_KeyDown;
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
Tb3 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 70) };
groupBox.Controls.Add(Tb3);
Tb3.KeyDown += Tb3_KeyDown;
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
Tb4 = new TextBox() { Width = 40, Height = 10, Text = "Something", Location = new Point(75, 90) };
groupBox.Controls.Add(Tb4);
Tb4.KeyDown += Tb4_KeyDown;
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)
{
// / call a method to do something using the Tb.text as argument
}
private void Tb3_KeyDown(object sender, KeyEventArgs e)
{
// / call a method to do something using the Tb.text as argument
}
private void Tb2_KeyDown(object sender, KeyEventArgs e)
{
// / call a method to do something using the Tb.text as argument
}
private void Tb1_KeyDown(object sender, KeyEventArgs e)
{
// call a method to do something using the Tb.text as argument
}
private void button1_Click(object sender, EventArgs e)
{
this.Controls.Add(GetGroupBox(++count));
}
先谢谢你。
1条答案
按热度按时间mlmc2os51#
从你的描述和代码来看,有很多东西缺失:
看起来您的问题是您正在创建一个新组,并且可能稍后将其分配给窗体。如果是这种情况,您可以在GetGroupbox方法中调用+=。另一种方法是在GetGroupBox过程中将所有TextBox示例添加到列表中,然后再执行+=。
现在,foreach很糟糕,你在tbx1上迭代,在那个上下文中tbx2是什么?
我建议你学习调试(通过断点)和评估你的代码行为。这将加快你的编码。