1

我目前正在编写一个从 xml 动态创建表单的 C# 程序。当前的 xml 包含我需要的 67 个字符串。但是,当 for 循环达到 34 或 35 时,它会返回 null。代码如下

for(int x =0; x < 67: x++){
CheckBox sue = (CheckBox)GetChildAtPoint(new Point(760, loc));
loc = loc + 20;
          }

我已经手动检查了表格,那里有一些东西,我正在使用最新的框架。我还发布了用于动态发布复选框和标签的代码。

 for (int x = 0; x < cnt; x++)
        {

            /*creating the form*/
            String edit = "e1";
            String template = "t1";
            this.Controls.Add(new Label() {Text = data[x], Width=540,     Name = x.ToString(), Location = new Point(20, loc) });
            this.Controls.Add(new CheckBox() {Checked = true, Width = 20, Name = edit, Location = new Point(560, loc) });
            this.Controls.Add(new CheckBox(){ Width = 20, Name = template, Location = new Point(760, loc)});


            loc = loc + 20; 


        }

在我看来,唯一合乎逻辑的事情是 GetChildAtPoint 是有限制的,而 xml 格式是企业网站的标准 site.xml 文件。无论如何完成这将对我有很大帮助。

4

2 回答 2

0

假设 cnt >= 67

这是枚举控件的一种不寻常的方式,仅按名称查找控件不是更容易吗?

例如,将名称设置为“CheckBoxAtLocx”,然后使用Controls["CheckBoxAtLocx"]

我会考虑这样做的其他方法是在创建时将所有控件添加到列表中。

所以这条线

this.Controls.Add(new CheckBox(){ Width = 20, Name = template, Location = new Point(760, loc)});

变成

var TempCheckbox = new CheckBox(){ Width = 20, Name = template, Location = new Point(760, loc)}
MyCheckboxList.Add(TempCheckbox); //Keep a reference for later
this.Controls.Add(TempCheckbox);

或者我会使用标签属性并存储其他信息,例如标识符

于 2013-04-03T16:19:06.857 回答
0

是的,GetChildAtPoint 仅适用于可见区域。几乎可以与鼠标位置一起使用。

我认为您将不得不考虑另一种方法:

for (int i = 0; i < 67; ++i) {
  foreach (CheckBox c in this.Controls.OfType<CheckBox>()) {
    if (c.Bounds.Contains(new Point(0, loc))) {
      // do something
    }
  }
  loc += 20;
}

您可能需要考虑将控件的高度设置为 20 像素会导致重叠。

另一种方法是检查控件的名称:

for (int i = 0; i < 67; ++i) {
  string checkName = "CheckBox" + i.ToString();
  if (this.Controls.ContainsKey(checkName)) {
    CheckBox checkBox = this.Controls[checkName] as CheckBox;
  }
}

您必须将其添加到您的构建器中:

this.Controls.Add(new CheckBox() { Name = "CheckBox" + i.ToString(), etc...
于 2013-04-03T16:22:00.397 回答