control on a form

G

Guest

Hi, I was wondering if there is a way to find out if a control exist on a form.
I have the control name (btnApply) and I would like to do something like...
form.controls("btnApply").exist as boolean. I know I could probably get
there by looking in each control of the form control collection but I'm
trying to find a shortcut.

Thanks!
 
J

Jared

dim tx as textbox

try
tx = directcast(MyContainer.Controls("YourControl"),textbox)
catch
'do stuff
end try

Will need to do for all containers on form and there is probably better way
than catch
 
M

manish

try following code

int index = this.Controls.GetChildIndex(yourControlName, false);
if(index != -1)
{
//Control found}
else
{
//Control not foundMessageBox.Show("not Found");
}

If you need the found control use

Control ctrl = this.Controls[index];
 
G

Guest

Justicetrax Dev said:
Hi, I was wondering if there is a way to find out if a control exist on a form.
I have the control name (btnApply) and I would like to do something like...
form.controls("btnApply").exist as boolean. I know I could probably get
there by looking in each control of the form control collection but I'm
trying to find a shortcut.

If you have a reference to the control, then you can call the form's
Contains() method. e.g.:

Form form;
Control btnApply;
if (form.Contains( btnApply )) { .. }

However, this will only work if the control is a child of the form, not a
child of a control on the form. If that's the case, you can also do this:

if (btnApply.FindForm() == form) { .. }

However, if you do not have a reference to the control but only have its
name, then you need to recursively check all controls in the form. Such as:

public bool ControlExists( Control parentControl, string controlName )
{
bool exists = false;
if (parentControl != null)
{
foreach (Control control in parentControl.Controls)
{
exists = String.Compare( control.Name, controlName ) == 0;
if (exists) break;

exists = this.ControlExists( control, controlName );
if (exists) break;
}
}
return exists;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top