Lets consider you require to display the values of lookup field for your webpart form in a dropdown.
You can use it in your dropdown datasource:
where field is SPField and list is SPList
DropDownList ddl = new DropDownList();
ddl.ID = field.Id;
ddl.DataSource = DataSource(field, list);
Here it goes :
public ICollection DataSource(SPField Colfield, SPList lookupList)
{
string lookupField;
int num = 0;
SPFieldLookup lookup = (SPFieldLookup)Colfield;
lookupList = lookupList.ParentWeb.Lists[new Guid(lookup.LookupList)];
if (lookup != null)
{
lookupField = lookup.LookupField;
if (string.IsNullOrEmpty(lookupField))
{
lookupField = "Title";
}
}
else
{
return null;
}
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("ValueField", typeof(int)));
table.Columns.Add(new DataColumn("TextField", typeof(string)));
if (!lookup.Required && !lookup.AllowMultipleValues)
{
DataRow row = table.NewRow();
row[0] = 0;
row[1] = SPResource.GetString("LookupFieldNoneOption", new object[0]);
table.Rows.Add(row);
num++;
}
if (lookupList != null)
{
try
{
SPField field = lookupList.Fields.GetField(lookupField);
SPQuery query = new SPQuery();
StringBuilder builder = new StringBuilder("
builder.Append("\"/>
builder.Append("\"/>
query.ViewXml = builder.ToString();
SPListItemCollection items = lookupList.GetItems(query);
for (int i = 0; i < items.Count; i++)
{
string fieldValueAsText = field.GetFieldValueAsText(items[i][lookupField]);
if (!string.IsNullOrEmpty(fieldValueAsText))
{
DataRow row2 = table.NewRow();
row2[0] = items[i].ID;
row2[1] = fieldValueAsText;
table.Rows.Add(row2);
num++;
}
}
return new DataView(table);
}
catch (ArgumentException)
{
return null;
}
}
return null;
}
Don't forget to put your comments if it helps you
No comments:
Post a Comment