2012-07-26 15 views
0

我是初學者,談到asp.net。我從昨天開始試圖找到一個問題的答案:如何使用asp.net將一個gridview的rownumber作爲命令參數傳遞?如何使用asp.net將gridview的rownumber作爲命令參數傳遞?

我已經嘗試了很多方法,但都沒有工作(commandargument在代碼隱藏中爲null),所以我認爲這是適當的嘗試使用JavaScript函數(如果有比使用JavaScript更短,更清晰的方法, 請告訴我)。

這裏的功能:

 <script type = "text/javascript"> 
    function GetSelectedRow(lnk) { 
     var row = lnk.parentNode.parentNode; 
     var rowIndex = row.rowIndex - 1; 
     alert("RowIndex: " + rowIndex); 
     return rowIndex; 
    } 
</script> 

而且也:

<ItemTemplate> 
       <asp:Label ID="labelStatus" 
          runat="server" 
          Text='<%#Bind("Statut")%>' 
          CommandArgument='<%#"Eval(GetSelectedRow(lnk))"%>'> 
       </asp:Label> 
    </ItemTemplate> 

我需要的行號的原因是在OnRowCommand事件處理程序,以便能夠指定哪一行正在編輯。 (myGridView.EditIndex = Convert.Int16(e.CommandArgument.ToString());)。

預先感謝您:)

回答

0

你在這裏找到GridView和一個完整的例子OnRowCommand

+0

謝謝。但是我不明白CommandArgument在asp頁面中的顯式值歸屬在哪裏。這是我真正的問題:)我沒有找到如何將行號傳遞給命令參數。 – SunnyDay 2012-07-26 08:53:38

+0

你不需要通過你的命令參數 – 2012-07-26 08:55:48

0

可以在RowCreated處理程序做它在服務器端:

protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Find the control which fires the command 
     LinkButton button = (LinkButton)e.Row.Cells[0].FindControl("LinkButton1"); 

     button.CommandArgument = e.Row.RowIndex.ToString(); 
    } 
} 

現在在點擊LinkButton1之後,RowCommand事件將被觸發,並且您可以在handler

protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e) 
{ 
    int rowIndex; 
    if (int.TryParse(e.CommandArgument as string, out rowIndex)) 
    { 
     // Do something with row index 
    } 
} 
+0

有道理,你剛纔所說的,看起來不錯,乾淨,但它仍然無法正常工作,因爲e.CommandArgument.ToString()仍然爲空,在我的情況下(我不知道爲什麼)。謝謝你們,反正你們的建議很好。 – SunnyDay 2012-07-26 12:13:38

+0

你可以顯示你的網格標記(特別是事件訂閱和觸發命令事件的按鈕)和代碼嗎?這可能有助於我們確定問題。 – Andrei 2012-07-26 12:41:42

+0

我剛回來再次感謝你,我剛剛解決了我的問題,多虧了你。我照你告訴我的那樣做了,但由於我的一個小錯誤,它不起作用。但現在呢! Multumesc :) – SunnyDay 2012-07-26 12:49:06

相關問題