将 ListControl 的 DataValueField/TextField 绑定到多个列





5.00/5 (1投票)
概念 在 ASP.NET 论坛中经常被问到的一个问题是如何将 ListControl 的 DataTextField 或 DataValueField 绑定到多个列。
概念
在 ASP.NET 论坛中经常被问到的一个问题是如何将 ListControl 的 DataTextField 或 DataValueField 绑定到多个列。 经典的解决方案 是像这样在 "Select" 语句中构建你的字段: "select 'n°' & NumCustomer & ' : ' & NameCustomer as datatxt from <table>, <table>... 等" 并将其属性设置为 DataValueField = "datatxt" 或/和DataTextField = "datatxt"。
但是,一种更高级的原始方法 也是可能的:ListControl 是 DropDownList、ListBox、RadioButtonList 和 CheckBoxList 服务器控件等控件的基类。 本文档将介绍实现此任务的方法。 代码将同时以 VB.NET 和 C#.NET 两种语言展示。
代码
首先,让我们在 ASP.NET 页面上添加一个 ListBox,如下所示
<asp:ListBox ID="lstVendors" runat="server" />
然后,我们将添加一个 SqlDataSource 来从数据库中检索数据。 使用的数据库是 AdventureWorks DB,使用的表是 Purchasing.Vendor 表。
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
SelectCommand="SELECT TOP 5 [ActiveFlag], [VendorID], [Name] FROM [Purchasing].[Vendor]" />
UI 尚未设置,让我们转到代码隐藏文件。 在此之前,请注意 ListBox 没有指定 DataSource。 这是有意为之,因为绑定将在代码隐藏文件中手动完成。 在 ASP.NET 页面的 page_load 方法中,让我们添加以下代码
C#.NET
protected void Page_Load(object sender, EventArgs e)
{
// Configure the Listbox only once, the first time
if (!Page.IsPostBack)
{
// Manually execute the SqlDataSource Select method.
// The return value is an IEnumerable and the real return
// value is a DataView
DataView rows = (DataView)this.SqlDataSource1.Select(new DataSourceSelectArguments());
// If there is data in the DataView
if ((rows != null) && (rows.Count >= 1))
{
// Loop through the record
for (int i = 0; i < rows.Count; i++)
{
// Create a new ListItem with the:
// Text: VendorID
// Value: Name;ActiveFlag
ListItem li = new ListItem(
rows[i]["VendorID"].ToString(),
string.Concat(rows[i]["Name"].ToString(), ";", rows[i]["ActiveFlag"].ToString()
));
// Add the ListItem to the lstVendors
this.lstVendors.Items.Add(li);
}
}
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Configure the Listbox only once, the first time
If (Not Page.IsPostBack) Then
' Manually execute the SqlDataSource Select method.
' The return value is an IEnumerable and the real return
' value is a DataView
Dim rows As DataView = CType(Me.SqlDataSource1.Select(New DataSourceSelectArguments()), DataView)
' If there is data in the DataView
If (Not rows Is Nothing) AndAlso (rows.Count >= 1) Then
' Loop through the record
For i As Integer = 0 To rows.Count - 1
' Create a new ListItem with the:
' Text: VendorID
' Value: Name;ActiveFlag
Dim li As ListItem = New ListItem(rows(i)("VendorID").ToString(), String.Concat(rows(i)("Name").ToString(), ";", rows(i)("ActiveFlag").ToString()))
' Add the ListItem to the lstVendors
Me.lstVendors.Items.Add(li)
Next i
End If
End If
End Sub
希望本文能帮助你满足将 ListControls 的 DataTextField 或 DataValueField 绑定到多个列的需求。
此致