1

当我传递在 Gridview 中选择的值进行删除时,它会抛出 Input String is not in correct format 异常我的代码是,

    protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
   {
    if (e.CommandName.ToUpper().ToString() == "DELETEREC")
    {
        try
        {
            ViewState["id"] = e.CommandArgument.ToString().Trim();
            int r = Namespace.SPs.StoredProcedure(Convert.ToInt32(ViewState["id"])).Execute();//Exception thrown Here
            if (r > 0)
            {
                ClientMessaging("Record Deleted Successfully");
                Clear();
                fillgrid();
            }
        }
        catch (SqlException ex)
        {
            ClientMessaging(ex.Message);
        }
    }
}

请帮我解决这个问题

我的 SP 方法是,

    public static StoredProcedure StoredProcedure(int id)
      {
            SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("StoredProcedure",    DataService.GetInstance("TEST"), "");
           sp.Command.AddParameter("@Id", id, DbType.Int32);

            return sp;
       }
4

2 回答 2

1

如果您使用命令参数来获取 ID,则需要将其设置为 gridview 中的命令参数,例如CommandArgument='<%#Eval("ID")%>'

否则您可以使用 DaTaKey 获取 ID 字段,如下所示

<asp:gridview id="gridview1" runat="server" datakeynames="ID"
    ..... >
</asp:gridview>

然后在行命令中

protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.ToUpper().ToString() == "DELETEREC")
    {
        try
        {
            int index = gridview1.SelectedIndex;

            int ID = Convert.ToInt32(gridview1.DataKeys[index].Value.ToString());

            int r = Namespace.SPs.StoredProcedure(ID ).Execute();
            // do stuff 
        }
        catch (SqlException ex)
        {
            ClientMessaging(ex.Message);
        }
    }
}
于 2013-05-16T11:26:17.750 回答
1

如果e.CommandArgument是一个空字符串,你会在 Convert.ToInt32(ViewState["id"])

我将尝试以这种方式更改您的代码

    try
    {
        int resultID;
        if(Int32.TryParse(e.CommandArgument.ToString().Trim(), out resultID))
        {
             ViewState["id"] = e.CommandArgument.ToString().Trim();
             .....
        }
        else
            // handle the case of not an integer value

更新 看到 StoredProcedure 的代码和上面的代码,那么失败的下一个原因是在 StoredProcedure 中,它需要不同类型的参数(例如 NVARCHAR 而不是 INT)

于 2013-05-16T11:06:30.317 回答