0

Yo, do you guys have any idea on how to add something to variable name/id? I can't really explain that so I'll just paste my code and explain what I want to do, or maybe you have a better idea to how to resolve that.

int[] array = new int[9];
            for (int i=0; i < 9; i++)
            {
                j=i+1.ToString();
                FindViewById<Button>(Resource.Id.***Num1***).Click += (o,e)=> 
                {
                    Result.Text += "j"; 
                };          
            }    

I've got 9 buttons and all of them are numbered from 1 to 9. I wan't to create an array to avoid many lines of useless code. So the question is: how to add a number ( or a string ) to this "Num" id, so in every iteration there will be another slot of array fulled with another button click event. Is it even possible to do this this way? Thanks for an answer :>.

BartMass
  • 3
  • 2
  • 1
    I don't think this is a possibility. Please refer [this](https://stackoverflow.com/questions/20857773/create-dynamic-variable-name) – Nikhileshwar Mar 16 '20 at 10:11
  • Thanks for refer, that helped me (dictionary). – BartMass Mar 16 '20 at 10:17
  • Does this answer your question? [Finding a resource given its ID - as a variable](https://stackoverflow.com/questions/19472483/finding-a-resource-given-its-id-as-a-variable) – Peter B Mar 16 '20 at 10:19

1 Answers1

0

If you want to get a resource identifier from its name, you need to use Resources.GetIdentifier(). For example, assuming the ID of your button is Num5:

var buttonNumber = 5;
var resourceId = Resources.GetIdentifier($"Num{buttonNumber}", nameof(Resource.Id).ToLower(), _activity.PackageName);
var button = FindViewById<Button>(resourceId);

I hope it helps!