Tuesday, January 3, 2012

Binding Data to a LookUp Column without a single line of loop Using Server Side Object Model

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace LookUpWebPart.LookUpWebPart
{
[ToolboxItemAttribute(false)]
public class LookUpWebPart : WebPart
{
string strError = string.Empty;
DropDownList ddlConcepts;
protected override void Render(HtmlTextWriter writer)
{
writer.Write(strError);
try
{
writer.Write("<Table width='100%'>");
writer.Write("<Tr>");
writer.Write("<Td>");
ddlConcepts.RenderControl(writer);
writer.Write("</Td>");
writer.Write("</Tr>");
writer.Write("</Table>");
}
catch (Exception ex)
{
strError += ex.ToString();
}
}
protected override void CreateChildControls()
{
try
{
ddlConcepts = new DropDownList();
this.Controls.Add(ddlConcepts);
SPQuery sQuery = new SPQuery();
sQuery.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
SPListItemCollection myColl = SPContext.Current.Web.Lists["SharePoint 2010 Concepts"].GetItems(sQuery);
if (myColl.Count > 0)
{
ddlConcepts.DataValueField = "ID";
ddlConcepts.DataTextField = "Title";
ddlConcepts.DataSource = myColl.GetDataTable();
ddlConcepts.DataBind();
}
}
catch (Exception ex)
{
strError += ex.ToString();
}
}
}
}

No comments:

Post a Comment