【问题标题】:Loading multiple Groupboxes in the form using the button_click event使用 button_click 事件在表单中加载多个 Groupboxes
【发布时间】:2023-02-02 19:17:25
【问题描述】:

我希望使用 button_click 事件在 Windows 窗体应用程序中加载多个组框。

每次单击按钮时,表单中都应出现一个组框。请参考以下屏幕截图了解我的预期输出。

我无法使组框动态定位,因为第二个组框应该与第一个组框有一定距离。我想到了手动计算坐标并使用点数组作为位置,但我觉得应该有更好的方法来解决这个问题。

我已经定义了“int count=0”变量来计算按钮被点击的次数。基于此,我命名了新的组框。但我认为 count++ 行中使用的逻辑存在一些问题。它不在 1 之后。因此我只得到一个组框“groupBox1”。当我再次点击按钮时没有任何反应。

我感谢您的帮助。

谢谢

Screenshot of my expected output is attached here

int count=0;
private GroupBox GetGroupBox(int a)
        {
            GroupBox groupBox = new GroupBox();
            groupBox.Text = "groupBox"+(a.ToString());
            groupBox.Width= 200;
            groupBox.Height= 200;
            groupBox.Location = new Point(50,400);
            return groupBox;            
        }
private void button1_Click(object sender, EventArgs e)
        {              
            count++;                       
            this.Controls.Add(GetGroupBox(count));           
        }

Screenshot of my expected output is attached here

【问题讨论】:

  • 位置groupBox.Location = new Point(50,400);不能是常量,groupBox.Location = new Point(50 + count * (groupBox.Width + 10), 400);

标签: c# button groupbox


【解决方案1】:

因为你想从左到右创建盒子,你应该调整Left:说,第一个盒子应该有Left = 50,第二个Left = 270,3d Left = 490等。

代码:

const int deltaX = 20;
...
groupBox.Location = new Point(50 + (a - 1) * (groupBox.Width + deltaX), 400);
...

简化的实现可以是

int count = 0;

private GroupBox CreateGroupBox(int index) => new GroupBox() {
  Text     = $"groupBox{index}",
  Size     = new Size(200, 200),
  Location = new Point(50 + (index - 1) * (20 + 200), 400),
  Parent   = this, // Instead of Controls.Add()
}

private void button1_Click(object sender, EventArgs e) {
  CreateGroupBox(++count);  
}

【讨论】:

  • 非常感谢@Dmitry 的帮助。
猜你喜欢
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 2017-10-19
  • 2021-06-03
  • 1970-01-01
相关资源
最近更新 更多