原文链接:http://dotnet.aspx.cc/article/2cb1c6d7-2b22-4655-8922-2a8a053a66fa/read.aspx
前几天写了一个利用GridView显示主细表的例子,有网友询问如何一次编辑明细表数据所有数据?其实,如果对ASP.NET或者HTML比较熟悉的话,这种批量编辑数据的功能很容易实现。下面的例子使用隐藏表单域记录数据的标识id,对每个输入框的名字附加id信息,这样的话,数据对应起来比较简单。
例子中使用的数据库来自《ASP.NET 2.0 应用开发技术》一书。换成其它数据库也类似,看懂代码,怎么换就无妨了。
aspx:
<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" EnableViewState="true"
CodeFile="Default2.aspx.cs" Inherits="Default2" %>
利用GridView显示主细表并一次编辑明细表所有数据的例子
C#:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\aspxWeb.mdb;Persist Security Info=True";
OleDbConnection cn1;
protected void Page_Load( object sender, EventArgs e )
{
if (!Page.IsPostBack)
{
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
cn1 = new OleDbConnection(ConnectionString);
cn1.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Subject]", cn);
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
MasterGridView.DataSource = dr;
MasterGridView.DataBind();
dr.Close();
cmd.Dispose();
cn.Dispose();
cn1.Dispose();
cn = cn1 = null;
}
}
protected void MasterGridView_RowDataBound( object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView oGridView = (GridView)e.Row.FindControl("DetailGridView");
if (oGridView != null)
{
OleDbCommand cmd = new OleDbCommand("select top 10 * from Document Where pid = " + MasterGridView.DataKeys[e.Row.RowIndex].Value, cn1);
OleDbDataReader dr1 = cmd.ExecuteReader();
oGridView.DataSource = dr1;
oGridView.DataBind();
dr1.Close();
cmd.Dispose();
}
}
}
protected void DetailGridView_RowDeleting( object sender, GridViewDeleteEventArgs e )
{
GridView a = (GridView)sender;
Response.Write("您要删除的记录是:" + a.DataKeys[e.RowIndex].Value.ToString() + " TODO:执行删除动作");
// TODO:执行删除动作
}
protected void DetailGridView_RowCommand( object sender, GridViewCommandEventArgs e )
{
}
protected void Button1_Click( object sender, EventArgs e )
{
string Guids = Request.Form["guid"];
if (Guids == null || Guids.Equals(string.Empty))
{
Response.Write("没有数据可以修改。");
return;
}
string sql;
OleDbCommand cmd;
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
string[] ArrGuid = Guids.Split(',');
for (int i = 0 ; i 更新:id= " + ArrGuid[i] + " "+ Request.Form["Title" + ArrGuid[i].Trim()]);
}
cn.Close();
cn.Dispose();
}
}