access webcontrol dynamically from code behind - by constructing name

L

Leo Muller

Hi,

On my webform I have three webcontrols (textboxes).
question1
question2
question3

on the code behind, I want to add to one of these a value, e.g. number2.
I want to write something like this: Control("question" & 2).text =
"something"
Because I don't know yet which one I want to write to.
I could do a select case: case 2: question2.text = "something", but I am
sure there is a better way.

How can I do this?

Thanks,

Leo
 
C

Cowboy \(Gregory A. Beamer\) [MVP]

You can loop through the controls and set the value. This will reduce the
amount of code, especially when you have a lot of controls. The pseudocode
is like this:

//Loop through controls
//Test for textboxes (or whatever you want)
//When found, test for name of textbox against value
//When found, set the value

As I said, easier coding, but not as easy on the processor. The switch is
more efficient in most cases, and would be extremely efficient if you can
find the rule, rather than the exception. What I mean: If 90% of the hits
use a particular control, and you set that to case #1, you end up ignoring
most of the conditions 90% of the time, reducing the number of checks to
find the correct one. NOTE: I am talking about what is happening behind the
scenes, not how a switch looks in code.

So, yes, you can make it easier on yourself by making it harder on the
processor. If this becomes far more maintainable for you, the lost cycles
may well be worth it.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
 
P

Paul Glavich [MVP - ASP.NET]

Control myControl1 = FindControl("TextBox2");
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
 

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

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top