使用Javascript进行gridview的Rowindex

时间:2012-03-16 07:31:34

标签: c# javascript asp.net gridview navigateurl

我尝试了很多组合,以便能够在下面的代码中获得行索引,应该写下面的内容“这就是我想要通过行索引”的部分。

            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
                AutoGenerateColumns="False" DataKeyNames="Id,BookName" DataSourceID="SqlDataSource1"
                Width="800px" CssClass="Gridview">
                <Columns>
                    <asp:TemplateField HeaderText="BookName" SortExpression="BookName" ItemStyle-Width="250px">
                        <ItemTemplate>
                            <asp:HyperLink ID="hlk_Bookname" runat="server" Enabled='<%# !Convert.ToBoolean(Eval("Reserve")) %>'
                                Text='<%# Bind("BookName") %>' NavigateUrl='javascript:doYouWantTo("THIS IS WHERE I WANT TO PASS ROWINDEX ")'></asp:HyperLink>
                        </ItemTemplate>                            
                    </asp:TemplateField>

.. .. ..

1 个答案:

答案 0 :(得分:1)

您可以使用RowDataBound。属性row包含rowindex

代码

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType==DataControlRowType.DataRow)
    {
        ((HyperLink)e.Row.FindControl("hlk_Bookname"))
        .NavigateUrl=string.Format("javascript:doYouWantTo({0})",e.Row.RowIndex));
    }
}

<强> ASPX

<asp:gridview id="GridView1"
        onrowdatabound="GridView1_RowDataBound" 
......

修改

如果有更好的解决方案可以解决您的问题。我想你正试图再次发明轮子。我想你可以查看RowCommand事件。您可以将其与RowCreated结合使用。您可以看到示例here。或者你可以这样做:

代码

protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="Add")
    {
      int index = Convert.ToInt32(e.CommandArgument);
      GridViewRow row = ContactsGridView.Rows[index];
      //What ever code you want to do....
    }
} 
//Set the command argument to the row index
protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];
      addButton.CommandArgument = e.Row.RowIndex.ToString();
    }
}

<强> ASPX

<asp:gridview id="GridView1" 
              onrowcommand="GridView1_RowCommand"
              OnRowCreated="GridView1_RowCreated"
              runat="server">

              <columns>
                <asp:buttonfield buttontype="Link" 
                  commandname="Add" 
                  text="Add"/>

希望这有帮助..