在 ASP.NET 2.0 中将 DropDownList 嵌套到 Gridview 以进行更新
在 ASP.NET 2.0 中将 DropDownList 嵌套到 Gridview 以更新一列

引言
在本文中,我将演示如何在 asp.net 2.0 中将 DropDownList 嵌套到 Gridview 以更新数据。需要创建一个 ITemplate,它可以用于表示和编辑 Gridview 中的数据。我使用一个标签在 ItemTemplate 中表示 City 列,并在 EditItemTemplate 中使用一个 DropDownList 来编辑它。
背景
当我使用 Gridview 时,我会问自己是否可以将 DropDownList 嵌套到 Gridview 以更新数据,现在我做到了,我将这种喜悦与大家分享!
逐步操作
1、将数据绑定到 Gridview 来自 SqlDataSource1,DataSource 是 (Northwind--Customers[CustomerID、CompanyName、City、ContactName]),我向 Northwind 添加了一个新的表 City[CityId,City],如下所示: 2、向 GridView 添加一个 TemplateField 列,在 ItemTemplate 字段中添加一个标签,并设计如下所示:
3.1、现在在 EditItemTemplate 字段中添加一个 DropDownList,并将其 DataSource 设置为 SqlDataSource2(Northwind--City[City]),如下所示:
3.2、然后单击“选择数据源...”并按如下所示配置:
3.3、然后单击“编辑数据绑定...”并按如下所示配置:
4、Default2.aspx 的完整代码请参见 DataBind.zip。
使用代码
配置 SqlDataSource1 如下
SelectCommand="SELECT [CustomerID], [CompanyName], [City], [ContactName] FROM [Customers]" UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [City] = @City, [ContactName] = @ContactName WHERE [CustomerID] = @CustomerID">
配置 SqlDataSource2 如下
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [City] FROM [City]">
配置 DropDownList 如下
DropDownList ID="DropDownList1" runat="server" Width="104px" SelectedValue='<%# Bind ("City") %>' DataSourceID="SqlDataSource2" DataTextField="City" DataValueField="City"
请记住,您需要自己向 Northwind 添加一个新的表 City[CityId,City]。
关注点
顺便说一下,我完成了这个案例,没有编写一行代码。vs.net2005 自动生成代码。
历史
这是我在 codeproject 上的第一篇文章!