当有东西时,GetChildAtPoint返回null

时间:2013-04-03 15:38:25

标签: c# winforms

我目前正在编写一个从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文件。无论如何要完成这将对我有很大帮助。

2 个答案:

答案 0 :(得分:0)

假设cnt> = 67

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

例如将名称设置为&#34; CheckBoxAtLocx&#34;然后使用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);

或者我使用tag属性并存储其他信息,例如Identifier

答案 1 :(得分: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...