62,047
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false" ShowHeader="true" OnDataBound="GridView1_DataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name").ToString() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = BindTest();
GridView1.DataBind();
}
}
protected DataTable BindTest()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Rows.Add("张三");
dt.Rows.Add("李四");
dt.Rows.Add("牛七");
dt.Rows.Add("王五");
dt.Rows.Add("马八");
return dt;
}
List<GridViewRow> list = new List<GridViewRow>();
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = GridView1.Columns.Count;
cell.Text = "第" + (e.Row.RowIndex + 1) + "行,这个是动态添加的";
gvr.Cells.Add(cell);
list.Add(gvr);
}
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (list.Count > 0)
{
int index = list.Count - 1;
for (int i = GridView1.Rows.Count - 1; i >= 0; i--)
{
if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
{
GridView1.Controls[0].Controls.AddAt(i + 2, list[index]);
index--;
}
}
}
}