This is one of those things that I always forget about and end up having to debug. (Also for those planning to do MCTS, I guarantee that there will be a question about this one ;) )
While it is technically possible to databind to a SPListItemCollection, when you try to refer to any of the SPListItem fields by name you’ll end up with an error similar to this:
[ArgumentException: Value does not fall within the expected range.]
Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName) +161
Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex) +56
Microsoft.SharePoint.SPListItem.GetValue(SPField fld, Int32 columnNumber, Boolean bRaw) +319
Microsoft.SharePoint.SPListItem.GetValue(String strName, Boolean bThrowException) +111
Microsoft.SharePoint.SPListItem.GetValue(String strName) +39
Microsoft.SharePoint.SPListItem.get_Title() +41
So using code like this won’t work:
SPList listData = SPContext.Current.Web.Lists[ListName];
SPView view = listData.Views[ViewName];
_theList.DataSource = listData.GetItems(view);
_theList.DataTextField = DataTextField;
_theList.DataValueField = DataValueField;
_theList.DataBind();
The SPListItemCollection provides a GetDataTable() method that converts the SPLIstItemCollection into a datatable that is much easier to use with databinding.
So the revised code looks like this:
_theList = new DropDownList();
SPList listData = SPContext.Current.Web.Lists[ListName];
SPView view = listData.Views[ViewName];
_theList.DataSource = listData.GetItems(view).GetDataTable();
_theList.DataTextField = DataTextField;
_theList.DataValueField = DataValueField;
_theList.DataBind();