c# – 以当前形式存在控制?

前端之家收集整理的这篇文章主要介绍了c# – 以当前形式存在控制?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要找出当前形式中是否存在具有某些名称的组件.
我在字符串变量中有组件的名称,如果它不存在,我需要创建它.
我用这个代码
Control c = Controls.Find(New,true)[0];   //najiti komponenty

        if (c == null) {}

但它给了我错误,索引超出了数组的范围.
我知道这段代码很糟糕,但我不知道写得好,谷歌也不帮我.

解决方法

Find方法返回一组控件,即Control [].您正在尝试访问空数组的第一个元素,从而导致IndexOutOfRangeException
你应该试试:
Control[] controls = Controls.Find(New,true); 
if (controls.Length > 0) 
{
    //logic goes here
}
else 
{
    //no components where found
}
原文链接:https://www.f2er.com/csharp/243265.html

猜你在找的C#相关文章