SharePoint Development Blog

Nick Boumans
View my LinkedIn Profile Follow me on Twitter View my Profile on FaceBook View my projects on CodePlex View my presentations on SlideShare



Recent posts

Tags

Categories

Navigation

Pages

Archive

Blogroll

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Loading UserControls (.ASCX) in a Web Part

One of the things we are missing is the ability to Visual Design WebParts in Visual Studio. We can load a UserControl into a WebPart by calling the Page.LoadControl method. It's a best practice to make a directory in your virtual directory called usercontrols and place the UserControls in it to load it from a WebPart. Note that this is the key concept of the SharePoint SmartPart.

[code:c#]
 private UserControl usercontrol;
private Button button;
private TextBox textbox;
private Label label;

public UserControlWebPart()
{
}

protected override void CreateChildControls()
{
    try
    {
        usercontrol = (UserControl)Page.LoadControl(@"/_controltemplates/usercontrols/MyUserControl.ascx");
        this.Controls.Add(usercontrol);
        if (usercontrol != null)
        {
            button = (Button)usercontrol.FindControl("Button1");
            button.Click += new EventHandler(button_Click);
            label = (Label)usercontrol.FindControl("Label1");
            textbox = (TextBox)usercontrol.FindControl("TextBox1");
        }
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry("WebParts", "Custom WebPart" + ex.ToString());              
    }
}

void button_Click(object sender, EventArgs e)
{
    label.Text = textbox.Text;
}

 

Posted: Apr 07 2008, 00:00 by Nick Boumans | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Web Parts