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;
}