Ken

Ken

  • 0
  • 110
  • 0

How can I convert a Control to a specific type like Button?

May 29 2021 12:15 AM
Hello.  I am building controls dynamically on a form based on some config data I read.  Originally I had code like:
  1. public Button GetElementButton(string elementID, string text) {  
  2.   Element elem = GetElement(elementID);  
  3.   if (elem == nullreturn null;  
  4.   
  5.   Button ret = new Button();  
  6.   ret.Text = text;  
  7.   ret.Location = elem.location;  
  8.   ret.Size = elem.size;  
  9.   return ret;  
  10. }  
  11.   
  12. public Label GetElementLabel(string elementID, string text) {  
  13.   Element elem = GetElement(elementID);  
  14.   if (elem == nullreturn null;  
  15.   
  16.   Label ret = new Label();  
  17.   ret.Text = text;  
  18.   ret.Location = elem.location;  
  19.   ret.Size = elem.size;  
  20.   return ret;  
  21. }

  22. Button myButton = GetElementButton("btn.score.p1", "Score");
    myButton.Click += (sender, e) => { Game.Score(1); };
    Controls.Add(myButton);
 I hate repeating myself though.  It occurred to me I could (I thought) do: 
  1. public Control GetElementControl(string elementID, string text) {    
  2.   Element elem = GetElement(elementID);    
  3.   if (elem == nullreturn null;    
  4.     
  5.   Control ret = new Control();    
  6.   ret.Text = text;    
  7.   ret.Location = elem.location;    
  8.   ret.Size = elem.size;    
  9.   return ret;    
  10. }  
  11.   
  12. Button myButton = (Button)GetElementControl("btn.score.p1""Score");  
  13. myButton.Click += (sender, e) => { Game.Score(1); };
  14. Controls.Add(myButton);  
But they all appear blank, no text.  Then when I click the button, it crashes with: 
  1. System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.Control' to type 'System.Windows.Forms.Button'.'  
 So I guess one can go Button -> Control but not Control -> Button.  Do I have to go back to a method for each type, or does someone know a way to achieve the dynamic creation so I don't have to repeat?  
 
 Thanks! 

Answers (2)