2012-03-16 29 views
1

我嘗試了很多組合以便能夠在下面的代碼中獲取rowIndex,應該在下面寫入「這是我要通過ROWINDEX的位置」部分。使用Javascript GridView的Rowindex

  <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

您可以使用RowDataBound。該物業row包含後面

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

編輯

如果你的問題更好的解決方案的rowIndex

代碼。我認爲你正試圖再次發明輪子。我想你可以看看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"/> 

希望這有助於..

+0

謝謝你的回答,可我問你,如果我的方法可能會更好?,我有超鏈接在我的GridView中,當超鏈接點擊時,我顯示一個JavaScript的我ssage(doYouWantTo如上),那麼如果是的話,這個javascript代碼點擊一個看不見的asp.net按鈕來運行ac#函數來將點擊的行插入數據庫,所以我問上面的問題找到並將rowindex傳遞給c#函數,do你覺得有沒有更好的辦法? – HOY 2012-03-16 07:57:58

+1

已更新答案 – Arion 2012-03-16 08:15:47

+0

作爲替代方案,如果您希望將其全部寫入標記,則可以使用以下語法: 'onclick ='<%#「myFunction(」+ Container.DataItemIndex +「)」%>'' – BornToCode 2013-10-27 08:42:24