gridview模板列事件中如何获得行号

本文介绍了两种在ASP.NET GridView的模板列事件中获取行号的方法。方法一是利用NamingContainer属性,在checkboxChanged事件中获取当前行的值。方法二是通过设置CommandArgument和CommandName属性,然后在RowCommand事件中捕获行号。具体实现包括在RowCreated事件中为LinkButton设置CommandArgument,并在RowCommand事件中根据CommandArgument获取行号。

例如,模板列中放入checkbox等,点击事件如何获得点击的是哪一行?,方法有很多,但第一种方法效率最高:

 

方法一:利用NamingContainer属性:

GridView模板列有一checkbox,checkbox的AutoPostBack属性为True,在checkboxChanged事件中可通过如下代码获取当前行某列的值:

protected void gridCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox t = (CheckBox)sender;
        int Index = ((GridViewRow)(t.NamingContainer)).RowIndex;//获得行号
        response.write(ModifyGridView.Rows[Index].Cells[4].Text.ToString().Trim());
    }

 

 

方法二:利用CommandArgument 和CommandName属性

(本博客中另一篇文章中也有提到详细做法:http://blog.youkuaiyun.com/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"];
         }
     }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值