Sunday, 10 March 2013

Programmatically Display List data in Web part getting List Name & filed Name from Edit Web Part Properties textbox in SharePoint 2010

To display the list data in a web part, open Visual Studio 2010 & create a Web Part Solution. The Web Part solution will appear as shown below


Now in the .cs file i.e. “DisplayListData.cs” file of the web part, we will declare a Personalizable Control which creates a Text box in the Edit Web Part Properties. If we want multiple values we can declare it again & save the value in other string as shown below

//Create a textbox in the Edit Web Part Properties to get the List Name
[Category("Custom Properties"),
Personalizable(PersonalizationScope.User),
WebBrowsable(true),
WebDisplayName("List Name"),
WebDescription("Enter List Name")]
//Get the value from the textbox & save it in the string
public string sListName { get; set; }

//Create another textbox in the Edit Web Part Properties to get the field name
 [Category("Custom Properties"),
Personalizable(PersonalizationScope.User),
WebBrowsable(true),
WebDisplayName("Column Name"),
WebDescription("Enter List Column Name")]
//Get the value from the textbox & save it in the string
public string sListColumnName { get; set; }


Now create the Label Controls to display the items in the web part

Literal ltrl = new Literal();
Label lblListName = new Label();
Label lblColumnName = new Label();
Label lblDisplayError = new Label();

protected override void CreateChildControls()
{
ltrl.Text = "";
lblListName.Text = "List Name entered : " + sListName;
lblListName.Font.Bold = true;
lblColumnName.Text = "List Column Name entered : " + sListColumnName;
lblColumnName.Font.Bold = true;
lblDisplayError.Text = "";
this.Controls.Add(lblListName);
this.Controls.Add(lblColumnName);
this.Controls.Add(lblDisplayError);
try
{
if (sListName != null && sListColumnName != null)
{
using (SPWeb currentWeb = SPContext.Current.Web)
{
SPList oList = currentWeb.Lists[sListName];
if (oList != null)
{
ltrl.Text = "Title<hr style='width:100px;text-align:left;'>";
foreach (SPListItem item in oList.Items)
{
ltrl.Text += "<i>" + item[sListColumnName] + "</i><br>";
}
}
}
}
else
{
lblDisplayError.Text = "Edit the Webpart and enter list name";
}
this.Controls.Add(ltrl);
}
catch (Exception ex)
{
lblDisplayError.Text = ex.Message.ToString();
}
}
protected override void Render(HtmlTextWriter writeHtml)
{
try
{
lblListName.RenderControl(writeHtml);
writeHtml.Write("<br /><br />");
lblColumnName.RenderControl(writeHtml);
writeHtml.Write("<br /><br />");
ltrl.RenderControl(writeHtml);
}
catch (Exception ex)
{
//Log
}
}


Now bulid the Solution & deploy in your web application. Add our custom created web part on the page & go to “Edit Web Part Properties” of that web part. Here we can see our custom created text boxes.

No comments:

Post a Comment