0

I am developing android application using xamrin and C# I am stuck when I create multiple buttons dynamically and assign them id. When I click on the button I get same id for all the Button. Any one can tell me how to create button with id so each button can be identified using id at runtime.

btnViewSupplier = new Button(this);
                            btnViewSupplier.Text =Convert.ToString(supplierInformationList[i]);
                            btnViewSupplier.Gravity= GravityFlags.Left;
                            btnViewSupplier.TextSize =18;
                            btnViewSupplier.ScrollBarSize = 20;
                            btnViewSupplier.SetBackgroundColor(Android.Graphics.Color.ParseColor("#29abe2"));
                            btnViewSupplier.SetTextColor(Android.Graphics.Color.White);
                            btnViewSupplier.Id=supplierID[i];

        public void callToview()
        {
            AppCode.ProfileId = Convert.ToInt32(btnViewSupplier.Id);
            Console.WriteLine("viewclicked");
            StartActivity(typeof(SupplierView));
        } 
schweerelos
  • 2,189
  • 2
  • 17
  • 25
Barry
  • 33
  • 11
  • after doing your tests, please consider to choose the answer that best fits with your purposes. thank you – Stefano Sep 11 '15 at 07:46
  • We need the full code. It looks like you're creating your buttons in a loop with the index `i` using the list `supplierID`. Are you sure this list has different numbers and your loop is working properly? We cannot see that from your code. – Racil Hilan Sep 11 '15 at 15:34
  • I was able to figure out. I had given reference of button out side of the method. so, just have to give reference Button btnViewsupplier; before crating instance of button. and it worked any ways thanks for replying me – Barry Sep 12 '15 at 20:29

2 Answers2

0

You could try creating random number and assigning it to ID property of button like this:

        Random rand = new Random();
        int id = rand.Next(1000000000, 999999999);

To avoid duplicates you can put generated ids in collection and after rand.Next call check if number is already generated.

arsena
  • 1,935
  • 19
  • 36
0

If I well understood your question, I'd go for using tags instead of id(s): Android lets you tag any view with anything you like (even custom objects) so you can recognize elements as you were working with id(s).

Here you find a good example of tag usage.

Hope this can help :)

Community
  • 1
  • 1
Stefano
  • 156
  • 3
  • 14