Get List name from SPLookupField

Background

The other day I had given a task of getting the list name of the SPLookup field. At the first it was little difficult to digest. But then i google a lot for the same and gave up. Finally, I have posted this on SharePoint forum and voila!!! got the answer in 30 mins as compared to my search of 2 days. Anyways lets see how it works.

Scenario

Let me explain the requirement first. We have one master list named “Master” with fields as Title, Description. The other custom list “CustomList” which has “Master” list as lookup column. Now in a webpart I have enumerate all the columns for “CustomList”. Which was piece of cake. But next thing was to enumerate the related data like, if it is SPChoiceField, SPBooleanField, SPLookupField then have to enumerate all the values for that field. Again for SPChoiceField and SPBooleanField it was piece of cake. But for lookup field it is possible only if the column name in “CustomList” is same as “Master” list. Other wise you have to hard code” the master list name which I didn’t wanted at all.

Code Example

To enumerate all the lists in a current site by populating the DropDownList.

SPWeb web = SPContext.Current.Site.OpenWeb();
SPListCollection lists = web.Lists;
    foreach (SPList list in lists)
        if (list.Hidden == false)
            ddl.Items.Add(list.Title);

To enumerate all the columns of “CustomList” in DropDownList’s selection change event.

if (ddl.SelectedIndex >= 0)
{
	list = web.Lists[ddl.SelectedValue];

	ddlFld.Items.Add(new ListItem("None", "None"));

	foreach (SPField field in list.Fields)
	{
		if (field.Hidden == false && field.ReadOnlyField == false && (field.GetType().Name == "SPFieldChoice" || field.GetType().Name == "SPFieldLookup" || field.GetType().Name == "SPFieldBoolean"))
			ddlFld.Items.Add(new ListItem(field.Title, field.InternalName));
	}

	ddlFld.SelectedIndex = ddlFld.SelectedIndex >= 0 ? 0 : -1;
}

Note: I have added extra filter for field types

Get the list of lookup list item values on selection change of field’s DropDownList if type of it is “SPLookupField”

list = web.Lists[ddl.SelectedValue];
string fld = list.Fields[ddlFld.SelectedValue].GetType().Name;
if (fld == "SPFieldLookup")
{
	SPFieldLookup fldLook = (SPFieldLookup)list.Fields[ddl.SelectedValue];
	SPList lst = web.Lists[new Guid(fldLook.LookupList)];
	foreach (SPListItem item in lst.GetItems())
	{
		sVal += "," + item["Title"] != null ? item["Title"].ToString() + ":" + fld.Replace("SPField", "") : "";
	}
}

Note: “:” added value can be useful when this is used in CamlQuery. You can ignore this if it is not required.

Reference

http://social.technet.microsoft.com/Forums/en-US/sharepoint2010general/thread/8eabd27b-ed98-4857-a302-d44e213e9d5a

Tagged with: ,