Using Custom ASP.NET Controls in a SharePoint Web Part
You also can add a custom controls “ascx” files which is allowing you to put your controls, html layout, css, javascripts and events handlers, so you can create your own control and you add whatever you want of ASP.NET controls and server side codes, but first you have to change trust level on the web.config of your application to Full.
You will find trust tag in the web.config and the default level is WSS_Minimal change it to Full
<trust level="Full" originUrl="" />
Then you can create the Control with or without a code behind and this is a sample control I called it MyControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits="MyControl" %>
<asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
The code behind in C# called MyControl.ascx.cs
using System;
public partial class MyControl : System.Web.UI.UserControl
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text;
}
}
After that you have to put your control files (.ascx) and the code behind if you use code behind (.cs or .vb) in the application folder which is usually under C:\Inetpub\wwwroot\wss\Virtual Directory\{Port Number} , and you can put your controls in a folder called Controls just to put the controls in one place and then load this control in your web part and add it
using Microsoft.SharePoint.WebPartPages;
namespace MyWebPart
{
public class Hello : WebPart
{
protected override void CreateChildControls()
{
Controls.Add(Page.LoadControl("/Controls/MyControl.ascx"));
base.CreateChildControls();
}
}
}
Then build your web part and deploy it like first sample.