Access object with a name

  • Thread starter Thread starter Sergey Atun
  • Start date Start date
S

Sergey Atun

Hi,
How can I access object with a name like this:

string ObjectName = "TextBox1";
TextBox(ObjectName).Text = "bla bla bla"

Thanks.
 
Hi Sergey,
How can I access object with a name like this:

string ObjectName = "TextBox1";
TextBox(ObjectName).Text = "bla bla bla"

As far as I understand this "pseudocode" you mean:

Find an Textbox on my form and set the Property "Text" to "bla bla bla".
Is this correct!?


<code>
foreach(Control c in this.Controls)
{
if (string.Compare(c.Name, "textBox1") == 0)
{
if (c is TextBox)
{
TextBox tb = (TextBox) c;
tb.Text = "bla bla bla";
}
}
</code>
 
Sergey,

You have two choices here in general. The first is to place each
reference to a control in a Hashtable (or a Dictionary if you are using .NET
2.0) and then key it on whatever you wish (the name, a number, etc, etc).

The other option is to use reflection on the class containing the
control, and then expose that (however, the class doesn't always have to
have a class level reference to the control for it to be visible).

Of course, in environments like ASP.NET, you might be provided with a
mechanism such as this already.

Hope this helps.
 
I saw that you laready got the answer of your question. Bare in mind,
though, that control don't haveto have names. Especialy in the case of
dynamicaly created controls porbably no one bothers of setting names
 
Back
Top