2

I have an application page where there are 52 consecutively named text boxes to allow the entry and display of weekly demand numbers for a year. My question is is there a way to "parameterize" a control (text box in this case) name so that I can loop through them instead of having to list out all 52?

For instance, I am currently verbosely listing them all out like this:

IEnumerable<DemandPattern> demandPattern = db.DemandPatterns.Where(x => x.DemandPatternID == demandPatternID);
txtBox1.Text = demandPattern.Where(x => x.Week == 1).Select(x => x.Demand).FirstOrDefault().ToString(); 
txtBox2.Text = demandPattern.Where(x => x.Week == 2).Select(x => x.Demand).FirstOrDefault().ToString();
...
txtBox51.Text = demandPattern.Where(x => x.Week == 51).Select(x => x.Demand).FirstOrDefault().ToString();
txtBox52.Text = demandPattern.Where(x => x.Week == 52).Select(x => x.Demand).FirstOrDefault().ToString();

I know I could wrap this in a for loop and replace the week # with the i variable, but how to deal with the textbox name...

for (int i = 1; i <= 52; i++)
    {
        txtBoxi.Text = demandPattern.Where(x => x.Week == i).Select(x => x.Demand).FirstOrDefault().ToString();
    }

I know there's got to be a better way to do this... This is an asp.net web app.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
Matthew Carr
  • 105
  • 10
  • 2
    Which technology? Winforms? Wpf? Asp.net? – Sriram Sakthivel Jun 01 '14 at 08:54
  • Can you just create textboxe on each iteration and add to some container (or bind it to the some grid like component) instead of having them all hardly placed in the app page? – Victor Jun 01 '14 at 08:57
  • Consider making a `List`. – Superbest Jun 01 '14 at 09:10
  • It's possible to use Reflection to emit IL such that you create a runtime-generated class with a number of properties. In your case, a property for each week. Then it could use a PropertyGrid as the UI. In your case, it would even handle the 1-in-6ish case of there being 53 weeks in the year without any further complications. – ClickRick Jun 01 '14 at 10:55

1 Answers1

3

Assuming it's asp.net :

for (int i = 1; i <= 52; i++)
    {
    var myTb= <FormId>.FindControl("txtBox"+i.ToString()) as TextBox;
    if (myTb == null) continue;
    myTb.Text = demandPattern.Where(x => x.Week == i).Select(x => x.Demand).FirstOrDefault().ToString();
    }

Notice - findcontrol is not recursive.

if you do want recursive (which means that textbox is not a direct child of form control) then - use this recursive method : https://stackoverflow.com/a/4955836/859154

How should I know if I should search it recursivly ? check this https://stackoverflow.com/a/15189759/859154

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792