1.在模板列中放一button和textobx,textbox用来存放产品名,将button的commandname设置为deletee 并且在html中将他的CommandArgument属性和RowIndex进行绑定:
<asp:TemplateField HeaderText="产品名">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# bind("productid") %>'></asp:TextBox>
<asp:Button ID="Button3" runat="server" CommandName="deletee" Text="Button" CommandArgument='<%# DataBinder.Eval(Container,"RowIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
后台中输出模板列中textbox中的值(保存的产品的id):
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "deletee")
{
int i = Convert.ToInt32(e.CommandArgument.ToString());
// int i = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;//(该方法不需要html中的绑定,取id.刚刚看到的,加上来,好方法.......)
TextBox tb = (TextBox)GridView1.Rows[i].FindControl("textbox3");
string str = tb.Text.Trim();
Response.Write(str);
}
}
注解:
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
e.CommandSource傳的是按下去的Button,不過由於傳回的是Object,就得自行轉成Button,但由於我們想知道的是RowIndex,而Button是包含在GridViewRow內,所以透過NamingContainer傳回目前的GridViewRow,但傳回的是Control,所以需在轉成GridViewRow後才能有RowIndex property。
原理是:将当前行索引和Button的commandargument绑定,用的时候只要取出当前行的索引即可......
gridview的rowcommand事件和datalist的itemcommand事件相似..........