前台添加一模版列,里面添加一个Button

Code
<asp:TemplateField HeaderText="测试">
<ItemTemplate>
<asp:Button ID="Button1" CommandName="btn" runat="server" Style="position: relative" Text="Button" />
</ItemTemplate>
</asp:TemplateField>


后台

Code
protected void gv_Company_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "btn"){
int index = Convert.ToInt32(e.CommandArgument);
DataKey key = this.gv_Company.DataKeys[index];
string str = key.Value.ToString();
}
}
//行数据绑定
protected void gv_Company_RowDataBound(object sender, GridViewRowEventArgs e){
if (e.Row.RowType == DataControlRowType.DataRow){
Button bt = new Button();
bt = (Button)e.Row.Cells[6].FindControl("Button1");
bt.CommandArgument = e.Row.RowIndex.ToString();
}
}
那么,如果是在GridView里已经设置了LinkButton为事件处理按钮,将通过以下方法获取索引
protected void gv_Company_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "btn"){
GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));
object result = (object)gv_Company.DataKeys[drv.RowIndex][int];//int为DataKeys位置
}
}
注:
e.CommandSource获得当前行触发命令的控件,强转为Control,
再找该控件的父控件,就得到Cell,再父控件就得到GridviewRow 然后在下面就对这个row进行相应的操作吧。