首先添加具有图像按钮模板列在里面:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Srl"
DataSourceID="EntityDataSource1" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/Left.gif" CommandName="Add" />
</ItemTemplate>
</asp:TemplateField>
<%--Other columns--%>
</Columns>
</asp:GridView>
然后在GridView1_RowDataBound事件处理程序设置按钮CommandArgument划船指数:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton button = (ImageButton)e.Row.FindControl("ImageButton1");
button.CommandArgument = e.Row.RowIndex.ToString();
}
}
终于在GridView1_RowCommand事件处理程序切换ImageButton imageUrl和CommandName,并执行任何您想要添加和删除行的操作:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
ImageButton button = (ImageButton)e.CommandSource;
switch (e.CommandName)
{
case "Add":
// Use selectedRow to add your rows
button.ImageUrl = "~/images/down.gif";
button.CommandName = "Remove";
break;
case "Remove":
// Use selectedRow to remove your rows
button.ImageUrl = "~/images/left.gif";
button.CommandName = "Add";
break;
}
}