2009-01-07 82 views
0

我在我的aspx頁面上有一個gridview使用一系列ASP.NET LinkBut​​ton對象設置OnRowCommand事件來處理使用CommandName屬性的邏輯。我需要訪問GridViewRow.RowIndex來從選定的行中檢索值,並注意它是一個非公開的GridViewCommandEventArgs對象的成員,同時調試應用程序訪問GridViewCommandEventArgs對象的非公共成員

有沒有一種方法可以訪問這個屬性是一個更好實施?

這裏是我的源代碼:

aspx頁面:

<asp:GridView ID="MyGridView" runat="server" OnRowCommand="MyGirdView_OnRowCommand"> 
    <Columns> 
     <asp:TemplateField> 
      <ItemTemplate> 
       <asp:LinkButton 
       id="MyLinkButton" 
       runat="server" 
       CommandName="MyCommand" 
       /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

代碼背後

protected void MyGirdView_OnRowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    //need to access row index here.... 
} 

UPDATE:
@brendan - 我得到了下面的編譯錯誤的以下行代碼:

「無法將類型 'System.Web.UI.WebControls.GridViewCommandEventArgs' 到 'System.Web.UI.WebControls.LinkBut​​ton'」

LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource); 

我稍微修改了代碼,並下面的解決方案工作:

LinkButton lb = e.CommandSource as LinkButton; 
GridViewRow gvr = lb.Parent.Parent as GridViewRow; 
int gvr = gvr.RowIndex; 

回答

1

不是在世界上最清潔的事情,但這個是我如何在過去做到了。通常情況下,我會把這一切全部弄清楚,但我會在這裏把它分解,所以更清楚。

LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource); 
GridViewRow gr = (GridViewRow) lb.Parent.Parent; 
var id = gr.RowIndex; 

基本上你會得到你的按鈕,並從單元格向上移動鏈中的按鈕到單元格。

這裏是一個行版本:

var id = ((GridViewRow)((LinkButton)((GridViewCommandEventArgs)e).CommandSource).Parent.Parent).RowIndex; 
+0

我提供了一個跟進你的答案 – 2009-01-07 19:44:38