在平时的实际项目中,为了减少往返提交数据,可以一次编辑 GridView 的所有行,这样大大提高用户使用产品的体验。下面就讲解何一次编辑 GridView 的所有数据行。在下面的例子中,数据库使用《ASP.NET 2.0应用开发技术》一书中Site\App_Data\下的 ASPNET20Book.mdb 数据库。例子中的数据更新方式使用 SqlDataSource 数据源控件的UpdateCommand属性,但此方法同样适用于存储过程,SQL 语句等。
C#
<%@ Page Language="C#" Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
string ClassNameArray = { "大学", "中学", "高中" };
//初始化原来的值
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView drv = (System.Data.DataRowView)e.Row.DataItem;
RadioButtonList rbl = (RadioButtonList)e.Row.FindControl( "txtGender");
if (rbl != null)
{
if ((bool)drv[ "Gender"])
{
rbl.Items.FindByText( "男").Selected = true;
}
else
{
rbl.Items.FindByText( "女").Selected = true;
}
}
DropDownList ddl = (DropDownList)e.Row.FindControl( "txtClassName");
if (ddl != null)
{
ddl.Items.FindByText(drv[ "ClassName"].ToString()).Selected = true;
}
}
}
// 初始化项目列表
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl( "txtClassName");
ddl.DataSource = ClassNameArray;
ddl.DataBind();
}
}
//处理提交的数据
protected void XianhuiMeng_Click(object sender, EventArgs e)
{
foreach (GridViewRow&nbs