Code Project

Link Unit

Monday, September 07, 2009

DataBinding: 'Microsoft.SharePoint.SPListItem' does not contain a property with the name

When trying to bind the 'Extension' column of a custom Sharepoint List to the DropdownList , I was facing the error :

DataBinding: 'Microsoft.SharePoint.SPListItem' does not contain a property with the name 'Extension'

In case I tried the following it ran successfully

using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Departments"];
cboDepartment.DataSource = list.Items;
cboDepartment.DataValueField = "Title"; // List field holding value
cboDepartment.DataTextField = "Title"; // List field holding name to be displayed on page
cboDepartment.DataBind();
}

So, I believe that whatever it is tryed to bind through DataTextField and DataValueField is supposed to be a property of the object we are binding to. For instance, SPListItem do have Title and ID properties, but it does not have 'Extension' property (in the meaning of the SPListItem class member).

So the following solutions were tried.

Solution #1

SPWeb site = SPContext.Current.Web;
DropDownList cboExtensions = new DropDownList();
SPList list = site.Lists["ImageExtensionList"];
SPListItemCollection lstCollection = list.Items;
cboExtensions.DataSource = lstCollection.GetDataTable();
cboExtensions.DataValueField = "Extension"; // List field holding value
cboExtensions.DataTextField = "Extension"; // List field holding name to be displayed on page
cboExtensions.DataBind();
this.Controls.Add(cboExtensions);


Solution #2

SPWeb site = SPContext.Current.Web;
DropDownList cboExtensions = new DropDownList();
SPList list = site.Lists["ImageExtensionList"];
foreach (SPListItem listRecords in list.Items)
{
//ListItem tempItem = listRecords["Extension"].ToString();
ListItem tempItem = new ListItem(listRecords["Extension"].ToString(), listRecords["Extension"].ToString());
cboExtensions.Items.Add(tempItem); //ddlFromSPList is the name of the dropdown list
}

Conclusion:
Whenever Title or ID is specified it will work without any issue. When the ListItemCollection is bounded to the DropDownList ,it is expecting Valuefield and TextField to be Properties. "Title" and "ID" are properties of List , hence it worked without any issue.

So the simple solution is to get the DataTable from the ListCollection or Get the items of the list , iterate the list and add the items to DropDownlist.

Hope it Helps
Jatinder Singh
Post a Comment