2012-05-04 42 views
4

我在做什么 - 在imagebutton点击重置用户密码。ASP GridView在按钮点击获取行值

到目前为止完成 - 添加GridViewCommandEventHandler - 它的正确触发。使用来自MSDN的代码。我得到一个空字符串(“”)为我的e.CommandArgument,并且它在运行时抛出一个错误(无法解析“”为int)。

我可以看到在调试器中有一个'rowIndex'属性被存储(正确地为我的点击)在e的其他地方,我可以访问它吗?我会认为MSDN的代码会起作用 - 我还做了其他事情来做出这个错误或者另一种解决方法吗?谢谢。

void resetpassword(Object sender, GridViewCommandEventArgs e) 
{ 
    // If multiple ButtonField columns are used, use the 
    // CommandName property to determine which button was clicked. 
    if (e.CommandName == "resetpass") 
    { 
     // Convert the row index stored in the CommandArgument 
     // property to an Integer. 
     int index = Convert.ToInt32(e.CommandArgument); 

     // Retrieve the row that contains the button clicked 
     // by the user from the Rows collection. Use the 
     // CommandSource property to access the GridView control. 
     GridView GridView1 = (GridView)e.CommandSource; 
     GridViewRow row = GridView1.Rows[index]; 

     String usrname = row.FindControl("username").ToString(); 

aspx页面代码:

<asp:TemplateField HeaderText="Reset Password"> 
       <ItemTemplate> 
        <asp:ImageButton ID="ibtnReset" runat="server" CausesValidation="false" 
         CommandName="resetpass" ImageUrl="~/Images/glyphicons_044_keys.png" Text="Button" /> 
       </ItemTemplate> 
       <HeaderStyle Width="70px" /> 
       <ItemStyle HorizontalAlign="Center" /> 
      </asp:TemplateField> 

事件添加代码:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 
    { 
     GridView1.RowCommand += new GridViewCommandEventHandler(this.resetpassword); 
    } 

回答

4

要么通过CommandArgument(假设你要传递的主键字段名为PK):通过您ImageButtonNamingContainer

<asp:TemplateField> 
    <ItemTemplate>     
     <asp:ImageButton runat="server" ID="ibtnReset" 
     Text="reset password" 
     CommandName="resetpass" 
     CommandArgument='<%# Eval("Pk") %>' 
    </ItemTemplate> 
    </asp:TemplateField> 

或获取GridViewRow的参考:

WebControl wc = e.CommandSource as WebControl; 
GridViewRow row = wc.NamingContainer as GridViewRow; 
String usrname = ((TextBox)row.FindControl("username")).Text; 

您也可以通过为的rowIndex CommandArgument:

CommandArgument='<%# Container.DataItemIndex %>' 

ButtonField类自动填充CommandArgument属性与相应的指标值。对于其他命令按钮,您必须手动设置命令按钮的CommandArgument属性。

+0

感谢ButtonField/ImageButton上的注释 - 现在我知道为什么那部分不工作!第一个选择,它完美的工作。 – Volvox

4

我认为你缺少CommandArgument='<%# Container.DataItemIndex %>'

为您的代码。

<asp:ImageButton ID="ibtnReset" runat="server" CausesValidation="false" 
     CommandArgument='<%# Container.DataItemIndex %>' 
     CommandName="resetpass" ImageUrl="~/Images/glyphicons_044_keys.png" 
Text="Button" /> 

以下是关于SO ASP.NET GridView RowIndex As CommandArgument的问题以供进一步阅读。

ButtonField类自动使用适当的索引值填充CommandArgument 属性。

Here is the MSDN source

+0

@Volvox:为了进一步阅读'ButtonField',我在更新中提供了MSDN链接。 – jams

+0

感谢您的协助!我会检查出来的。 – Volvox