User controls are rapid way to develop custom functionality. There are 3 steps involved in creating user controls. This article walks through step by step on creating user controls which displays currently logged in user in SharePoint 2010.
1. Create and deploy user control
2. Register user control in the target
3. Insert the user control wherever required.
Step 1: Create and deploy user control
1. Fire up visual studio 2010, Create a new Empty SharePoint Project.
2. Add an user control to the Project, say "MyUserControl", Project structure will look like this:
1. Fire up visual studio 2010, Create a new Empty SharePoint Project.
2. Add an user control to the Project, say "MyUserControl", Project structure will look like this:
3. Lets build the control now. Go to the code view, Insert a <DIV> and label. Set some CSS styles as like this:
<div id="Main" style="border:1; background-color:#2C84CA; font-size: 25px; color:White;">
<asp:Label ID="lblUserName" runat="server" Text="0"></asp:Label>
</div>
4. The idea is: Lets display the currently logged in user name in the label. Get in to the code behind file (.cs) add this little code.
namespace MyUserControl.ControlTemplates.MyUserControl
{
public partial class MyUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
string currentUser = "Current User Name:" + SPContext.Current.Web.CurrentUser.Name;
lblUserName.Text = currentUser;
}
}
5. Build and deploy the project. This will create new folder in 14 hive's Controltemplate's folder (In my case it was: \14\TEMPLATE\CONTROLTEMPLATES\MyUserControl\MyUserControl.ascx
Step 2: Register user control in the target
We have our user control ready now. Next step is insert the user control wherever needed. Here, Lets add it to a SharePoint page. say, Default.aspx. By the way, You can load the user control wherever you want, like in Pages, Master pages, Page layouts, and even in Web parts (use Page.LoadControl method)
1. Open SharePoint designer, Open the target site, and then Default.aspx in advanced mode.
2. Register the user control at the top of the page.<%@ Register TagPrefix="MyUserControl" TagName="UserName" Src="~/_controltemplates/MyUserControl/MyUserControl.ascx" %>
Step 3: Insert the user control wherever required.
Now, we can include the user control in the page, Here I've done like this: <MyUserControl:UserName id="MyUserControl1" runat="server" />
Now, we can include the user control in the page, Here I've done like this: <MyUserControl:UserName id="MyUserControl1" runat="server" />
Finally The User Control Display Username on the registered Page .see below image,
Note:
You don't need to add the user control assemblies in <SafeControl> entry under web.config file explicitly, as all the controls in side CONTROLTEMPLATES folder of 14 hive are trusted by default!
eNjoy SharePoint !!!






No comments:
Post a Comment