access form control propertys via control name as string

P

Peted

if i have the name of a control in a string is there anyway to access
its properties ?

Eg

Button btnClickme1;

i want to do this

("btnClickme" + "1").text = "newtext";

is this possible

i am trying to do this becasue i have 8 buttons on the form, they are
only differentiated in the name by a number

Eg

btnClickme1, btnClickme2 etc etc

and i dont know any way of selectively accessing the properties within
a for loop

any advice appreciated


thanks

Peted
 
G

Guest

for (int i = 1; i < 9;i++)
this.Controls["btnClickme" + i.ToString()].Text = "newtext";

will change the text on all the buttons.
 
P

Peter Duniho

i want to do this

("btnClickme" + "1").text = "newtext";

is this possible

In the form containing the controls:

for (int i = 0; i < cbuttonMax; i++)
{
Controls.Find("btnClickme" + i.ToString()).Text = "newtext";
}

Generally speaking, if you know the type of control you're dealing with,
you can always cast it to the appropriate type and access the property
directly. In this case you don't even need to cast, since the Text
property is in the base Control class returned by the Find() method.

Pete
 
P

Peter Duniho

In the form containing the controls:

for (int i = 0; i < cbuttonMax; i++)
{
Controls.Find("btnClickme" + i.ToString()).Text = "newtext";
}

Sorry...shouldn't post off the top of my head so late. :)

Of course, the reply from tony is correct. You can fix mine by indexing
the array returned by the Find() method (eg "Controls.Find("btnClickme"
+ i.ToString())[0].Text = "newtext";"), but that's overkill.

Note that whether you use Find() or the [] operator tony suggests, it is
better to check the returned value (non-empty array using Find(), non-null
result using []) before attempting to access the Text property. This will
prevent an exception in case there's some bug somewhere that causes your
index to wind up out of range of which controls are actually present.

Pete
 

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