在ASP.NET中,ListControl是一个基类,它为DropDownList、ListBox、RadioButtonList和CheckBoxList等服务器控件提供了基础。本文将介绍如何将这些控件绑定到数据库的多列数据。
通常,可以通过在SQL查询中使用字符串拼接的方式来实现这一目的,例如:
SELECT 'n°' & NumCustomer & ' : ' & NameCustomer AS datatxt FROM , ...
但是,还可以采用更高级的方法来实现这一功能。以下是在ASP.NET页面中添加ListBox控件的示例:
<asp:ListBox ID="lstVendors" runat="server" />
接下来,将添加一个SqlDataSource控件来从数据库中检索数据。这里使用的是AdventureWorks数据库,以及Purchasing.Vendor表。
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
SelectCommand="SELECT TOP 5 [ActiveFlag], [VendorID], [Name] FROM [Purchasing].[Vendor]" />
UI部分尚未设置,让转向代码后台。在ASP.NET页面的Page_Load方法中,将添加以下代码:
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
DataView rows = (DataView)this.SqlDataSource1.Select(new DataSourceSelectArguments());
if ((rows != null) && (rows.Count >= 1)) {
for (int i = 0; i < rows.Count; i++) {
ListItem li = new ListItem(
rows[i]["VendorID"].ToString(),
string.Concat(rows[i]["Name"].ToString(), ";", rows[i]["ActiveFlag"].ToString())
);
this.lstVendors.Items.Add(li);
}
}
}
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
Dim rows As DataView = CType(Me.SqlDataSource1.Select(New DataSourceSelectArguments()), DataView)
If (Not rows Is Nothing) AndAlso (rows.Count >= 1) Then
For i As Integer = 0 To rows.Count - 1
Dim li As ListItem = New ListItem(rows(i)("VendorID").ToString(), String.Concat(rows(i)("Name").ToString(), ";", rows(i)("ActiveFlag").ToString()))
Me.lstVendors.Items.Add(li)
Next i
End If
End If
End Sub