输入字符串的格式不正确。

时间:2013-05-16 11:00:20

标签: c# sql-server

当我在Gridview中传递所选的值以进行删除时,它会抛出输入字符串格式不正确异常我的代码是,

    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;
       }

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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

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

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

然后在Row Command中

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);
        }
    }
}