locked
Referencing Buttons Created in Code RRS feed

  • Question

  • Hi,

    I am having a problem where i have created a loop that creates buttons for a certain amount of times. I have specified everything about the button in the code but it can not make reference to them in the code because technically they do not exist while you are typing the code. Is there anyway to make reference to these buttons in the code in C#?  


    • Edited by kayz96 Tuesday, July 23, 2013 12:46 AM
    Tuesday, July 23, 2013 12:45 AM

Answers

  • If you create it, keep track of it!

    It's so easy to create a list of Controls (hint, hint) for holding this sort of thing.

    internal class Form1 : Form 
    {
       public Form1() 
       { 
          dynamicButtons_ = new List<Button>() ; 
    
          for ( int i = 0 ; i < 10 ; ++ i ) 
          {
             Button btn = new Button() ; 
             dynamicButtons_.Add( btn ) ; 
             . . . 
          }
    
          foreach( Button db in dynamicButtons_ ) 
             db.Enabled = false ; 
       } 
    
       private List<Button> dynamicButtons_ = null ; 
    
    }
    



    Regards, Phill W.

    • Marked as answer by Barry Wang Wednesday, July 31, 2013 7:48 AM
    Wednesday, July 24, 2013 12:00 PM

All replies

  • Are you adding them directly to the form or to a specified container?

    If you are adding them to a container, such as a panel, what is the name of the container?

    Are there any buttons on / in the form / container other than the ones that you created?

    It might be helpful if you posted your creation code and indicate what you want to do with the reference to the individual buttons.


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Tuesday, July 23, 2013 2:20 AM
  • If you create it, keep track of it!

    It's so easy to create a list of Controls (hint, hint) for holding this sort of thing.

    internal class Form1 : Form 
    {
       public Form1() 
       { 
          dynamicButtons_ = new List<Button>() ; 
    
          for ( int i = 0 ; i < 10 ; ++ i ) 
          {
             Button btn = new Button() ; 
             dynamicButtons_.Add( btn ) ; 
             . . . 
          }
    
          foreach( Button db in dynamicButtons_ ) 
             db.Enabled = false ; 
       } 
    
       private List<Button> dynamicButtons_ = null ; 
    
    }
    



    Regards, Phill W.

    • Marked as answer by Barry Wang Wednesday, July 31, 2013 7:48 AM
    Wednesday, July 24, 2013 12:00 PM