更新:2007 年 11 月
List 和 SelectionList ASP.NET 移动控件呈现基本的数据视图,并使用户能够选择数据项。
您可以将 List 或 SelectionList 移动控件绑定到 DataView 或 DataSet 对象,或者绑定到实现 IEnumerable 或 IListSource 的任何对象。若要将 List 或 SelectionList 移动控件绑定到 DataView 对象,请设置控件的 DataSource 属性,并调用其 DataBind 方法。下面的代码示例演示如何将一个控件绑定到包含名为 Titles 的表的 DataSet 对象。
myList.DataSource = ds.Tables["Titles"].DefaultView;
myList.DataBind();
或者,可以将 List 或 SelectionList 控件绑定到 DataSet 对象。为此,请将 DataMember 属性设置为表的名称。下面的示例与前一个示例是等同的。
myList.DataSource = ds;
myList.DataMember = "Titles";
myList.DataBind();
List 或 SelectionList 控件中的列表项可以绑定到两个数据值。一个数据值被绑定到列表项的 Text 属性,另一个数据值被绑定到其 Value 属性。通过设置 List 或 SelectionList 控件的 DataTextField (SelectionList.DataTextField) 和 DataValueField (SelectionList.DataValueField) 属性来配置列表项的绑定。List 控件使用其 Text 属性显示每个项。例如,如果想按其 CustomerName 属性显示每个项,请将 DataTextField 属性设置为 CustomerName。
您可能想将每个项显示为由若干数据值组成的摘要。为此,您可以处理 List 控件的 ItemDataBind 事件或 SelectionList 控件的 ItemDataBind 事件,并以编程方式设置 Text 属性。下面的代码示例演示如何将书籍信息呈现为书名和价格的组合。
private void List_OnItemDataBind(object sender,
ListDataBindEventArgs e)
{
e.ListItem.Text = String.Format ("{0} – {1}",
DataBinder.Eval (e.DataItem, "title"),
DataBinder.Eval (e.DataItem, "price", "{0:C}"));
}
在支持更丰富的呈现的设备上,您可以使用 List 控件的模板集来显示数据项的自定义视图。在模板模式下,List 控件的功能与 Repeater ASP.NET 服务器控件的功能类似。例如,您可以使用以下项模板显示书籍的详细视图。
<ItemTemplate>
<tr style="background-color:FFECD8">
<td>
<%# DataBinder.Eval(((MobileListItem)Container).DataItem, _
"title") %>
</td>
<td>
<%# DataBinder.Eval(((MobileListItem)Container).DataItem, _
"title_id") %>
</td>
<td>
<%# DataBinder.Eval(((MobileListItem)Container).DataItem, _
"type") %>
</td>
<td>
<%# DataBinder.Eval(((MobileListItem)Container).DataItem, _
"pub_id") %>
</td>
<td>
<%# DataBinder.Eval(((MobileListItem)Container).DataItem, _
"price", "{0}", "{0:C}") %>
</td>
</tr>
</ ItemTemplate >
有关模板集的更多信息,请参见模板集和模板化控件。