0

I have a loop that I need to create Entries dynamically, and with that, I need to setFocus() on a specifically Entry, and then, another one, etc.

How can I change the name of variables in runtime to I identify it?

for(i = 0; i < list.Count; i++)
{
  //the result that I want:
  Entry entry + i = new Entry(){ Placeholder = "Entry number" + i.ToString() };
}

//result
entry1 =  /* Placeholder */ "Entry number 1";
entry2 =  /* Placeholder */ "Entry number 2";
entry3 =  /* Placeholder */ "Entry number 3";

EDIT:

I forgot to put an Entry event that I need to use:

entries[i].Completed += (s, e) =>
{
   if (!entries[i].Text.Contains("\u00b2"))
   {
    entries[i].Text += "\u00b2";
   }
};
   entries[i].Focus();

when it enters in this event, it can't know how entry that I'm calling, always get the last entry of this array.

techie
  • 463
  • 4
  • 17

3 Answers3

2

the s in the event parameters is the sender - that is, the object that fired the event

entries[i].Completed += (s, e) =>
{
   var entry = (Entry)s;

   if (!entry.Text.Contains("\u00b2"))
   {
     entry.Text += "\u00b2";
   }
};
Jason
  • 86,222
  • 15
  • 131
  • 146
1

You would use some kind of collection, for example an array:

var entries = new Entry[3];
for(i = 0; i < list.Count; i++)
{
  //the result that I want:
  entries[i] = new Entry(){ Placeholder = "Entry number" + i.ToString() };
}

//result
entries[0] =  /* Placeholder */ "Entry number 1";
entries[1] =  /* Placeholder */ "Entry number 2";
entries[2] =  /* Placeholder */ "Entry number 3";

To know the called entry you can either cast the sender parameter like Jason suggests, var entry = (Entry)s. Or capture a variable:

// for loops require copying of the index to a local variable when capturing. 
var currentIndex = i; 
entries[i].Completed += (s, e) =>
{
   if (!entries[currentIndex].Text.Contains("\u00b2"))
   {
    entries[currentIndex].Text += "\u00b2";
   }
};

Variable names mostly exist before compilation, so asking how to change it at runtime is kind of a nonsensical question.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • I updated my question, I forgot to put a few lines that I'm struggling to do. Can you please edit your answer and include what I asked now? – techie Nov 07 '21 at 21:45
0

When you do

for (int i = 0; i < list.Count; i++)
{
    entries[i].Completed += (s, e) =>
    {
       if (!entries[i].Text.Contains("\u00b2"))
       {
          entries[i].Text += "\u00b2";
       }
    };
}

you "capture" that i variable in that event handler, not its value. This means that when that Completed event finally fires, it uses the latest known value of "i".

The solution is to copy the value to a new variable, declared inside the loop:

for (int i = 0; i < list.Count; i++)
{
    int j = i;
    entries[j].Completed += (s, e) =>
    {
       if (!entries[j].Text.Contains("\u00b2"))
       {
          entries[j].Text += "\u00b2";
       }
    };
}
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111