Friday, February 8, 2008

Create custom web part (part I)

Add a class library and set its output path (right click on the project name, properties, Built tab) to the bin folder of the sharepoint web site you want to deploy it on (wwwrootwss\VirtualDirectories\ [port#])

Add reference to System.Web
Add the following using statements
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.WebControls.WebParts
Inherit your class from WebPart class
------------------------------------------------------------
Sample:

namespace BilalWebParts
{
public class MyWebPart : WebPart
{
GridView gv;
protected override void CreateChildControls()
{
gv = new GridView();
this.Controls.Add(gv);
BindStudents();
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<table border='1' bordercolor='black'>");
writer.Write("<tr><td>");
writer.Write("Students List");
writer.Write("</tr></td>");
writer.Write("<tr><td>");
gv.RenderControl(writer);
writer.Write("</tr></td>");
writer.Write("</Table>");
}
protected void BindStudents()
{
string connectionString = "UID=sa;PWD=P@ssw0rd;Initial Catalog=test;Data Source=MOSS;";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from Students", con);
cmd.CommandType = CommandType.Text;

DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);

gv.DataSource = dt;
gv.DataBind();
}
}
--------------------------------------------------------------
Build your application
--------------------------------
Add the following line to safe control block in the web.config of the sharepoint website you want to add the webpart to.
<SafeControl Assembly="BilalWebParts" Namespace="BilalWebParts" TypeName="*" Safe="True" />
---------------------------------
Modify trust tag in web.config
<trust level="WSS_Medium" originUrl="" />
---------------------------------
Adding WebPart:
Open sharepoint site
Go to site settings, then go to webparts link under Galleries tab, click new and check BilalWebParts.MyWebPart then click populate gallery.
Go back to you site and Edit Page then Add a webpart, search for MyWebPart and click ok.Students List will apear
------------------------------------------------------------------

Best Regards

0 comments: