2009-01-07 79 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