How can you move ASP.Net controls to different places on the Web form at runtime?

前端 未结 5 1857
迷失自我
迷失自我 2021-01-01 01:41

Is there an accepted way to \"move\" a control.

My client wants to place a certain chunk of markup (representing some visual element) in one of several different pla

5条回答
  •  忘掉有多难
    2021-01-01 02:21

    I'd recommend using a placeholder control, moving your markup into a separate user control, then loading this at runtime and adding it to the relevant placeholder.

    Eg.

    // Load a user control
    MyControl userCtrl = (MyControl) LoadControl("~/Controls/MyControl.ascx");
    
    // Or create an instance of your control
    SubclassedControl subclassedCtrl = new SubclassedControl();
    
    // Do stuff with controls here
    userCtrl.LoadData();
    subclassedCtrl.Text = "Hello World";
    
    // Check which placeholder to add controls to
    PlaceHolder placeHolder = (foo=="bar") ? placeHolder1 : placeHolder2;
    
    // Add the controls
    placeHolder.Controls.Add(userCtrl);
    placeHolder.Controls.Add(subclassedCtrl);
    

    This will avoid cluttering up your page with unnecessary markup, and loading it at runtime will also avoid unnecessary confusion later, when another developer looks at the code and can't immediately see why a control is in one place in the markup, but renders on a completely different part of the page.

提交回复
热议问题