c# – ASP GridView在按钮点击时获取行值

我在做什么 – 在图像按钮上单击重置用户密码.

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

我可以在调试器中看到在e的其他地方存储了一个’rowIndex’属性(正确地为我的点击),我可以访问它吗?我认为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);
    }
传递CommandArgument(假设您要传递名为PK的主键字段):

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

或者通过ImageButton的NamingContainer获取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属性.

相关文章
相关标签/搜索