简体   繁体   English

访问GridViewCommandEventArgs对象的非公共成员

[英]Access Non-Public members of a GridViewCommandEventArgs object

I have a gridview on my aspx page set up the OnRowCommand event using a series of ASP.NET LinkButton object to handle the logic using the CommandName property. 我在aspx页面上有一个gridview,它使用一系列ASP.NET LinkBut​​ton对象来设置OnRowCommand事件,以使用CommandName属性来处理逻辑。 I need to access the GridViewRow.RowIndex to retrieve values from the selected row and notice it is a non-public members of the GridViewCommandEventArgs object while debugging the application 我需要访问GridViewRow.RowIndex以从选定的行中检索值,并在调试应用程序时注意到它是GridViewCommandEventArgs对象的非公共成员

Is there a way I can access this property of is theere a better implementation? 有没有一种方法可以访问此属性,这是更好的实现?

Here is my source code: 这是我的源代码:

aspx page: 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> 

code behind 背后的代码

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

UPDATE: 更新:
@brendan - I got the following compilation error on the following line of code: @brendan-在以下代码行中出现以下编译错误:

"Cannot convert type 'System.Web.UI.WebControls.GridViewCommandEventArgs' to 'System.Web.UI.WebControls.LinkButton'" “无法将类型'System.Web.UI.WebControls.GridViewCommandEventArgs'转换为'System.Web.UI.WebControls.LinkBut​​ton'”

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

I slightly modified the code and the following solution worked: 我稍微修改了代码,以下解决方案起作用了:

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

Not the cleanest thing in the world but this is how I've done it in the past. 这不是世界上最干净的事情,但这是我过去所做的事情。 Usually I'll make it all one line but I'll break it down here so it's more clear. 通常,我会全部写成一行,但在这里将其分解,这样更清楚。

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

Basically you get your button and move up the chain from button to cell, from cell to row. 基本上,您可以得到按钮,并从按钮到单元格,从单元格到行向上移动链。

Here is the one row version: 这是单行版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM