Question

I tried a lot of combinations to be able to get rowIndex in below code, What should be the written to below "THIS IS WHERE I WANT TO PASS ROWINDEX " part.

            <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>

.. .. ..

Was it helpful?

Solution

You can use RowDataBound. The property row contains the rowindex

Code behind

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" 
......

Edit

If there is a better solution for you problem. I think you are trying to invent the wheel again. I think you can have a look at RowCommand event. You can use it in combination with RowCreated. You can see an example here. Or you can do it something like this:

Code behind

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"/>

Hope this help..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top