Monday, September 06, 2010

Calling usercontrol in sharepoint webparts


Create the usual User Control in asp.net and calling into Share point is simple process that reduces the complexity of deploying and developing the web part.
Place the 2 text boxes and label to create simple add two number calculator in your
On click of the button result will be displayed on label.


protected void Button1_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
Label3.Text = (a + b).ToString();
}


Before using the user control check it on .aspx file by registering the user control in directives.

<%@ Register Src="~/Calculator.ascx" TagName="_userCntrl" TagPrefix="SP" %>

once you tested the user control on .aspx file,now you are ready to place the
user control design page calculator.ascx and source code file calculator.ascx.cs in to share point folder structure

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS

Now go to visual studio,select the Webpart template,


public class UserControlCalculator : System.Web.UI.WebControls.WebParts.WebPart
{
Control _cntrl;
string ErrorDesc;
public UserControlCalculator()
{
this.ExportMode = WebPartExportMode.All;
}

protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
_cntrl =Page.LoadControl("\\_layouts\\Calculator.ascx");
this.Controls.Add(_cntrl);

}
catch (Exception ex)
{
ErrorDesc = ex.Message.ToString();
}

}
protected override void Render(HtmlTextWriter writer)
{
try
{
_cntrl.RenderControl(writer);
}
catch (Exception ex)

{
writer.Write(ex.Message.ToString());
}
}


}