資料來源:Shadow和愉快的程式碼伙伴
目標功能:
點選GridView的CommandField後,在該列下面新增一列並把剛剛新增列移除掉
.aspx
<%@ Page Debug="true" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> |
<html xmlns="http://www.w3.org/1999/xhtml"> |
<form id="form1" runat="server"> |
<asp:SqlDataSource runat="server" id="sds_Categories" |
ConnectionString="<% ConnectionStrings:NorthwindChineseConnectionString %>" |
SelectCommand="SELECT [CategoryID], [CategoryName], [Description], [Picture] FROM [Categories]" |
<asp:GridView runat="server" ID="gvw_Categories" AutoGenerateColumns="False" |
DataKeyNames="CategoryID" DataSourceID="sds_Categories" |
onrowcommand="gvw_Categories_RowCommand" AllowPaging="True" PageSize="5" > |
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" |
InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> |
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" |
SortExpression="CategoryName" /> |
<asp:BoundField DataField="Description" HeaderText="Description" |
SortExpression="Description" /> |
<asp:TemplateField ShowHeader="False"> |
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" |
CommandName="Open" Text="此列下面增一列"></asp:LinkButton> |
.cs
using System.Collections.Generic; |
using System.Web.UI.WebControls; |
public partial class _Default : System.Web.UI.Page |
protected void gvw_Categories_RowCommand(object sender, GridViewCommandEventArgs e) |
if (e.CommandName == "Open") |
int currentIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex; |
if (ViewState["addIndex"] != null ) |
gvw_Categories.Controls[0].Controls.RemoveAt(Convert.ToInt32(ViewState["addIndex"])); |
int pageIndex = gvw_Categories.PageIndex; |
gvw_Categories.DataBind(); |
gvw_Categories.PageIndex = pageIndex; |
GridViewRow gvr = new GridViewRow(-1, 0, DataControlRowType.DataRow, DataControlRowState.Normal); |
TableCell cell = new TableCell(); |
cell.Text = "Hello World!!"; |
gvw_Categories.Controls[0].Controls.AddAt(currentIndex + 2, gvr); |
ViewState["addIndex"] = currentIndex + 2; |
protected void gvw_Categories_PageIndexChanging(object sender, GridViewPageEventArgs e) |
ViewState["addIndex"] = null; |
gvw_Categories.PageIndex = e.NewPageIndex; |
gvw_Categories.DataBind(); |
執行效果:
預設畫面

點選第一列

點選第二列

離婚證人
、
台北離婚證人
、
新竹離婚證人
、
彰化離婚證人
、
高雄離婚見證人
遺囑見證人
、
結婚證人