You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET GridView的RowCommand按钮无法触发函数求助

解决ASPX GridView按钮无法触发RowCommand事件的问题

以下是针对问题的具体排查和修复步骤:

1. 修复Page_Load中的数据绑定逻辑

页面回发时重复绑定GridView会破坏控件视图状态,导致事件无法触发。修改Page_Load方法,仅在首次加载时绑定数据:

protected async void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        await CargarTabla();
    }
}

protected async Task CargarTabla()
{
     string apiUrl = "http://localhost:5000/api/get/pagos";

     try
     {
         using (HttpClient client = new HttpClient())
         {
             HttpResponseMessage response = await client.GetAsync(apiUrl);

             if (response.IsSuccessStatusCode)
             {
                 string jsonResponse = await response.Content.ReadAsStringAsync();
                 List<ListadoPagos> pagos = JsonConvert.DeserializeObject<List<ListadoPagos>>(jsonResponse);
                 tablaPgos.DataSource = pagos;
                 tablaPgos.DataBind();
             }
             else
             {
                 // 处理请求失败的情况
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
}

2. 为GridView配置DataKeys属性

你在RowCommand中尝试通过DataKeys获取idpago,但GridView标签未声明DataKeys,导致运行时出错。修改GridView的ASPX代码:

<asp:GridView ID="tablaPgos" runat="server" AutoGenerateColumns="False" 
    OnRowCommand="tablaPgos_RowCommand" DataKeyNames="idpago">
    <columns>
        <asp:BoundField DataField="idpago" HeaderText="Id" />
        <asp:BoundField DataField="fechapago" HeaderText="Fecha de Pago" />
        <asp:BoundField DataField="codigoestudiante" HeaderText="Codigo del Estudiante" />
        <asp:BoundField DataField="nombre" HeaderText="Tipo de Pago" />
        <asp:BoundField DataField="monto" HeaderText="Monto" />
        <asp:TemplateField HeaderText="Acciones">
            <itemtemplate>
                <asp:Button ID="btnEliminar" runat="server" Text="Eliminar Pago" CommandName="Eliminar" CommandArgument='<%# Container.DataItemIndex %>'/>
            </itemtemplate>
        </asp:TemplateField>
    </columns>
</asp:GridView>

3. 修复按钮的HTML标签闭合

你的按钮标签末尾是'/,缺少闭合符号>,导致控件渲染异常无法注册点击事件,修正为完整的闭合标签/>(如上代码所示)。

4. 确保RowCommand方法唯一

你贴出了两个同名的tablaPgos_RowCommand方法,实际代码中需保留一个正确版本,建议保留包含删除逻辑的版本:

protected async void tablaPgos_RowCommand(object sender, GridViewCommandEventArgs e)
{
      if (e.CommandName == "Eliminar")
      {
          int rowIndex = Convert.ToInt32(e.CommandArgument);
          int id = Convert.ToInt32(tablaPgos.DataKeys[rowIndex].Value);
          await EliminarPagoAsync(id);
      }
}

private async Task EliminarPagoAsync(int idPago)
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            string apiUrl = $"http://localhost:5000/api/delete/pago/{idPago}";

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await httpClient.DeleteAsync(apiUrl);

            if (response.IsSuccessStatusCode)
            {
                lblMensaje.Text = "Pago eliminado exitosamente.";
                await CargarTabla();
            }
            else
            {
                lblMensaje.Text = "Error al eliminar el pago. Por favor, intente nuevamente.";
                await CargarTabla();
            }
        }
    }
    catch (Exception ex)
    {
        lblMensaje.Text = "Error: " + ex.Message;
    }
}

额外注意事项

  • 确保页面上的lblMensaje控件存在且ID正确(测试代码中出现lMensaje,注意拼写一致性)。
  • 异步方法中避免使用.Result,改用await防止线程死锁。

内容的提问来源于stack exchange,提问作者Andx45t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:06:00