Thursday, January 28, 2010

Display master-detail table using GridView and add a delete, open, close functions

aspx

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>




利用GridView显示主细表并添加打开、关闭功能







BorderWidth="1" OnRowDataBound="MasterGridView_RowDataBound" DataKeyNames="id"
ShowHeader="false">




栏目名称:<%#Eval("Title") %>',event)">隐藏

">
HorizontalAlign="left" DataKeyNames="id" AutoGenerateDeleteButton="true" OnRowCommand="DetailGridView_RowCommand"
OnRowDeleting="DetailGridView_RowDeleting" Width="720px">




/read.aspx">
<%#Eval("Title") %>
[<%# Eval("HitCount") %>]


HeaderStyle-Width="100px" ItemStyle-HorizontalAlign="Center" />











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 )
{

}
}


Note: EnableViewState = "true" is a must.

No comments:

Post a Comment