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

从GridView取DataKeys报“需要方法名”编译错误,代码结构是否有误?

错误原因

你遇到的编译错误完全是VB转C#的语法差异导致,和GridView控件配置无关,核心有3处语法问题:

  • C#访问索引器使用方括号[],VB才用圆括号(),你写的gvDestroy.DataKeys[index]("destroy_id")不符合C#语法规范
  • C#调用方法必须加圆括号,ToString是实例方法,你漏写()会被编译器识别为方法组,自然抛出「需要方法名」的错误
  • 第二处报错行的两个参数之间错误使用点号分隔,漏掉了逗号,同时同样存在ToString漏加()的问题

修正后的代码

后台事件代码(仅修改报错行,其余逻辑不变)

protected void gvDestroy_RowCommand(object sender, GridViewCommandEventArgs e)
{
    string sReturn;
    string sLoggedBy;
    if (e.CommandName == "Delete")
    {
        odsDestroy.DeleteParameters.Add("mod_by", Session["username"].ToString());
    }
    if (e.CommandName == "Destroy")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = gvDestroy.Rows[index];
        // 修正第一处报错
        sLoggedBy = cDestroyDP.fGetDestroy(gvDestroy.DataKeys[index]["destroy_id"].ToString()).Rows[0]["logged_by"].ToString();
        if (sLoggedBy == Session["username"].ToString())
        {
            lblError.ForeColor = System.Drawing.Color.DarkRed;
            lblError.Text = "Operator cannot log and destroy same controls!";
        }
        else
        {
            // 修正第二处报错,补全参数逗号和ToString括号
            sReturn = cDestroyDP.fDestroyControl(gvDestroy.DataKeys[index]["destroy_id"].ToString(), Session["username"].ToString()).ToString();
            if (sReturn != "0")
            {
                lblError.ForeColor = System.Drawing.Color.DarkRed;
                lblError.Text = sReturn;
            }
            else
            {
                gvDestroyed.DataBind();
                gvDestroy.DataBind();
            }
        }
    }
}

前台GridView绑定修正(如果你的页面使用C#语法)

原来的CommandArgument绑定用的是VB语法,需要改成C#写法:

<asp:Button ID="btnDestroy" runat="server" Text="Destroy" 
 CommandName="Destroy" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:39:03