Step 1: Open Visual
Studio 2010 | Add New Project | Sharepoint | Empty Sharepoint Project and named
is DevSanbox
Step 2: Choose your Web
App and choose deploy sanbox
Step 3: Add new item |
Web Part and named is DevSanbox
Step 4: code in
event CreateChildControls as
Code here
protected override void CreateChildControls()
{
Literal literalResult = new Literal();
this.Controls.Add(literalResult);
SPSite spSite = SPControl.GetContextSite(Context);
SPWeb spWeb =
spSite.OpenWeb();
SPList spList =
spWeb.Lists["Tasks"];
SPQuery spQuery=new SPQuery();
SPListItemCollection spListItemCollection
= spList.GetItems(spQuery);
foreach (SPListItem item in spListItemCollection)
{
literalResult.Text
+= item["Title"] + "||";
}
}
Step 5: Build project
and Package it
Step 6: Open your web
application => back to top level site, Click Site Actions | Site
Setting | Click “Solutions” link | Upload Solution
Step 7: Choose your
.WSP in bin folder and Active it
Step 8: Result as
Step 9: Add Web Part as
Step 10: Error appear
Step 11: Solve problem.
Replace code as
protected override void CreateChildControls()
{
Literal literalResult = new Literal();
this.Controls.Add(literalResult);
//SPSite spSite = SPControl.GetContextSite(Context);
//SPWeb spWeb =
spSite.OpenWeb();
using (SPWeb spWeb = SPContext.Current.Web)//Important
{
SPList spList =
spWeb.Lists["Tasks"];
SPQuery spQuery = new SPQuery();
SPListItemCollection spListItemCollection
= spList.GetItems(spQuery);
foreach (SPListItem item in spListItemCollection)
{
literalResult.Text
+= item["Title"] + "||";
}
}
}
Step 12:
Deactive Solution
Step 13: Upload solution
again and Active It
Step 14: Result as