get Control by Name

  • Thread starter Thread starter Maciej
  • Start date Start date
M

Maciej

U¿ytkownik "Sharon said:
Hi all

Is it possible to refer a control by his name programmatically?



Example:



I have text box and a button on a form

txtName

btnClick





And what I want to do is:



myForm.GetControl("txtName").text = "xxx"

myForm.GetControl("btnClick").text = "xxx"

You should use:
this.txtName.text="xxx";
and
this.btnClick.text="xxx";
 
Is it possible to refer a control by his name programmatically?
Yes, it is possible if you loop through the list of your controls and
compare their names with the name you are refering to.

private Control FindControlByName(string name)
{
foreach (Control c in this.Controls) //assuming this is a Form
{
if (c.Name == name)
return c; //found
}
return null; //not found
}
 
Hi all

Is it possible to refer a control by his name programmatically?



Example:



I have text box and a button on a form

txtName

btnClick





And what I want to do is:



myForm.GetControl("txtName").text = "xxx"

myForm.GetControl("btnClick").text = "xxx"
 
Well I thought that there is an option to go directly to the control by its
name,

This loop will increase the processing & presenting time since there are
lots of other controls on this form



By the way In JS there is a method

· getObjectByName: Method returns a registered object based on the
specified name.



Thank you anyway

Sharon
 
Well I thought that there is an option to go directly to the control by
its
name,

This loop will increase the processing & presenting time since there are
lots of other controls on this form

If you have many controls on the form, you can use for example Hashtable and
add all your Controls to it with their name as a key. Accessing items in a
hashtable is a constant time operation, so there is virtually no performance
hit if you use the hashtable.

On form.Load or elsewhere

this.controlHashtable = new HashTable();
foreach Control c in this.Controls
{
this.controlHashtable.Add(c.Name, c);
}

private Control GetControlByName(string name)
{
return this.controlHashtable[name] as Control;
}
 
Great idea
thank you !!!!


Lebesgue said:
Well I thought that there is an option to go directly to the control by its
name,

This loop will increase the processing & presenting time since there are
lots of other controls on this form

If you have many controls on the form, you can use for example Hashtable
and
add all your Controls to it with their name as a key. Accessing items in a
hashtable is a constant time operation, so there is virtually no
performance
hit if you use the hashtable.

On form.Load or elsewhere

this.controlHashtable = new HashTable();
foreach Control c in this.Controls
{
this.controlHashtable.Add(c.Name, c);
}

private Control GetControlByName(string name)
{
return this.controlHashtable[name] as Control;
}
 
Back
Top