Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exist control in current form?

Tags:

c#

winforms

I need to find out if component with some name exist in current form. I have name of the component in string variable and if it doesnt exist, i need create it. I use this code

Control c = Controls.Find(New, true)[0];   //najiti komponenty

        if (c == null) {}

But it gives me error that the index was outside the bounds of the array. I know this code is bad, but i dont know to write it good and google dont help me.

like image 589
Crooker Avatar asked Jan 06 '13 14:01

Crooker


2 Answers

Try using the Control.ContainsKey() Method, (pass a string variable containg the control name instead of the quoted text in my example):

if (!this.Controls.ContainsKey("MyControlName"))
{
    // Do Something
}
like image 44
XIVSolutions Avatar answered Oct 17 '22 07:10

XIVSolutions


Find method return an array of controls, i.e. Control[]. You are trying to access the first element of the empty array, thus resulting in IndexOutOfRangeException You should try:

Control[] controls = Controls.Find(New, true); 
if (controls.Length > 0) 
{
    //logic goes here
}
else 
{
    //no components where found
}
like image 136
Ilya Ivanov Avatar answered Oct 17 '22 08:10

Ilya Ivanov