我需要找出当前形式中是否存在具有某些名称的组件.我在字符串变量中有组件的名称,如果它不存在,我需要创建它.我用这个代码
Control c = Controls.Find(New, true)[0]; //najiti komponenty
if (c == null) {}
Run Code Online (Sandbox Code Playgroud)
但它给了我错误,索引超出了数组的范围.我知道这段代码很糟糕,但我不知道写得好,谷歌也不帮我.
Find方法返回一个控件数组,即Control[].您正在尝试访问空数组的第一个元素,从而导致IndexOutOfRangeException
您应该尝试:
Control[] controls = Controls.Find(New, true);
if (controls.Length > 0)
{
//logic goes here
}
else
{
//no components where found
}
Run Code Online (Sandbox Code Playgroud)
尝试使用Control.ContainsKey()方法(传递一个包含控件名称而不是我的示例中带引号的文本的字符串变量):
if (!this.Controls.ContainsKey("MyControlName"))
{
// Do Something
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9404 次 |
| 最近记录: |