我有一个列表,看起来像这样:
Movie Year
----- ----
Fight Club 1999
The Matrix 1999
Pulp Fiction 1994使用CAML和SPQuery对象,我需要从Year列中获得一个不同的项目列表,该列表将填充一个下拉控件。
在CAML查询中进行搜索似乎没有办法做到这一点。我想知道人们是如何实现这一目标的?
发布于 2009-02-18 16:35:07
另一种方法是使用DataView.ToTable-Method -它的第一个参数是使列表与众不同的参数。
SPList movies = SPContext.Current.Web.Lists["Movies"];
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='Year' /></OrderBy>";
DataTable tempTbl = movies.GetItems(query).GetDataTable();
DataView v = new DataView(tempTbl);
String[] columns = {"Year"};
DataTable tbl = v.ToTable(true, columns);然后,您可以继续使用DataTable tbl。
发布于 2010-12-29 18:25:15
如果您希望将不同的结果绑定到DataSource,并通过ItemDataBound events的e.Item.DataItem方法保留实际的项,那么DataTable方法将不起作用。相反,除了不想将其绑定到DataSource之外,还可以使用Linq来定义不同的值。
// Retrieve the list. NEVER use the Web.Lists["Movies"] option as in the other examples as this will enumerate every list in your SPWeb and may cause serious performance issues
var list = SPContext.Current.Web.Lists.TryGetList("Movies");
// Make sure the list was successfully retrieved
if(list == null) return;
// Retrieve all items in the list
var items = list.GetItems();
// Filter the items in the results to only retain distinct items in an 2D array
var distinctItems = (from SPListItem item in items select item["Year"]).Distinct().ToArray()
// Bind results to the repeater
Repeater.DataSource = distinctItems;
Repeater.DataBind();请记住,由于不存在对distinct查询的CAML支持,因此此页面上提供的每个示例都将检索SPList中的所有项。这对于较小的列表可能很好,但对于包含数千个列表标题的列表,这将严重影响性能。不幸的是,没有更优化的方法来实现同样的目标。
发布于 2009-02-18 11:05:40
在CAML中没有DISTINCT来填充您的dropdown,尝试使用如下所示:
foreach (SPListItem listItem in listItems)
{
if ( null == ddlYear.Items.FindByText(listItem["Year"].ToString()) )
{
ListItem ThisItem = new ListItem();
ThisItem.Text = listItem["Year"].ToString();
ThisItem.Value = listItem["Year"].ToString();
ddlYear.Items.Add(ThisItem);
}
}假设您的下拉列表名为ddlYear。
https://stackoverflow.com/questions/560550
复制相似问题