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.
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With