例如,模板列中放入checkbox等,点击事件如何获得点击的是哪一行?,方法有很多,但第一种方法效率最高:
方法一:利用NamingContainer属性:
GridView模板列有一checkbox,checkbox的AutoPostBack属性为True,在checkboxChanged事件中可通过如下代码获取当前行某列的值:
方法二:利用CommandArgument 和CommandName属性
(本博客中另一篇文章中也有提到详细做法:http://blog.csdn.net/Devillyd/archive/2010/07/20/5749510.aspx)
首先在gridview中关联事件
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" Font-Size="13px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" OnRowCreated="GridView1_RowCreated" >
创建模板列,并加入LinkButton 设置 CommandName
<asp:TemplateField HeaderText="上移" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="MoveUp" Text="上移"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="下移" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="false" CommandName="MoveDown" Text="下移" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
在cs文件中,重写RowCreated事件
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
LinkButton1.CommandArgument = e.Row.RowIndex.ToString();
LinkButton LinkButton2 = (LinkButton)e.Row.FindControl("LinkButton2");
LinkButton2.CommandArgument = e.Row.RowIndex.ToString();
}
}
最后在RowCommand事件中,就可以获得当前行号了
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MoveUp")
{
ViewState["MoveRow"]=e.CommandArgument;
TxtName.Text = (string)ViewState["MoveRow"];
}
if (e.CommandName == "MoveDown")
{
ViewState["MoveRow"] = e.CommandArgument;
TxtName.Text = (string)ViewState["MoveRow"];
}
}