关于使用 Winform ,向 panel 控件中动态添加一个 TextBox 控件,设置了 panel 的区域大小后,点击4次添加后,当 TextBox 控件填满了 panel 区域后,再次点击添加,第4次的控件与第5次添加的控件中间会有空行,如果连续点击添加没有空行出现,但是停顿后,再次点击添加,中间就又会出现空行
```c#
private int nextLocation1 = 0;
private int nextLocation2 = 0;
private int nextLocation3 = 0;
private int btnCilck = 0;
private void button1_Click(object sender, EventArgs e)
{
//for (int i = 0; i < 60; i++)
//{
AddControl(btnCilck.ToString());
//}
btnCilck++;
}
public void AddControl(string a)
{
TextBox textBox = new TextBox();
textBox.Text = a;
textBox.Name = $"textBox{nextLocation1}";
textBox.Location = new Point(10, nextLocation1);
textBox.Size = new Size(150, 20);
nextLocation1 += 30;
panel1.Controls.Add(textBox);
}
```
nextLocation1 += 30;
这里下断点调试下
【以下回答由 GPT 生成】
问题原因是在每次添加TextBox控件时,都会增加nextLocation1
的值,用来确定下一个TextBox的位置。然而,在点击按钮后,如果没有立即连续点击添加,nextLocation1
的值不会重置,而是保留了之前的高度。导致第四次和第五次添加的控件之间出现了空行。
为了解决这个问题,我们可以在每次点击按钮时,先判断是否需要重置nextLocation1
的值。如果当前nextLocation1
的值超过了Panel的高度,就将其重置为0。
以下是修改后的代码:
private void button1_Click(object sender, EventArgs e)
{
btnClick++;
if (nextLocation1 >= panel1.Height)
{
nextLocation1 = 0;
}
AddControl(btnClick.ToString());
}
这样修改后,当TextBox控件填满Panel区域后再次点击按钮添加时,就不会出现空行了。
【相关推荐】