0

I'm creating User controls based on which button is clicked, but trying to use as little code as possible to keep my project clean.

So instead of writing the same code in each button_click controller I planned to call the void WhichController

string ControlName = "UserControl";
string ControlNamePath = "FormProject.";

 private void button2_click(object sender, EventArgs e){
   int controllernumber += 3;
   WhichController();
 }

 private void WhichController(){
   var ControllerDisplay = ControlNamePath + ControlName + Controllernumber;
   ControllerDisplay Controllershow = new ControllerDisplay();
   panel1.Controls.Add(Controllershow);
 }

I keep getting ControllerDisplay is a variable but is used like a type. Is there anyway around this? Suggestion on method change are welcome.

CupOfJava
  • 441
  • 1
  • 5
  • 15
  • 1
    Well, according to `var ControllerDisplay = ControlNamePath + ControlName + Controllernumber;` we can see `ControllerDisplay` to be a *local variable* (of type `string`). However, in `ControllerDisplay Controllershow = new ControllerDisplay();` the same `ControllerDisplay` is a *type* of `Controllershow` local variable – Dmitry Bychenko Jan 09 '20 at 09:37
  • why not use a `Dictionar`? Then you can easily get a controller by its name: `panel1.Controls.Add(myDict[controllerToShow])`. – MakePeaceGreatAgain Jan 09 '20 at 09:39
  • @HimBromBeere I'm not sure I completely understand your approach. Might you care to elaborate more in an answer, or with a link ? – CupOfJava Jan 09 '20 at 09:47
  • Do you already have a class named "ControllerDisplay"? If rename you local variable "var ControllerDisplay" to some other name – Vijayanath Viswanathan Jan 09 '20 at 09:57
  • Is this what you want? https://stackoverflow.com/questions/648160/how-do-i-create-an-instance-from-a-string-in-c ? Another approach would be to use a switch statement in WhichController to create instances of your controls. – PaulF Jan 09 '20 at 09:57
  • Variable names cannot be used as types. Maybe you can define a property in UserControl to store "ControlNamePath + ControlName + Controllernumber". – 大陸北方網友 Jan 10 '20 at 01:43

0 Answers0