在查询中将数据类型nvarchar转换为数字时出错

时间:2015-08-21 13:20:10

标签: c# sql asp.net gridview

我想调用行的ACCOUNT_NO=ACCOUNT_NO|none|M,ADD1=ADD1|none|M,因为我想删除该行。

这是我的代码: -

ID

但我无法删除该行。当我尝试调试它时,在private void DeleteAttachment(string ID) { using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString())) { connection.Open(); string sql = "DELETE FROM EMP_ATTACHED_DOCUMENTS WHERE mkey= @ID"; using (SqlCommand cmd = new SqlCommand(sql, connection)) { cmd.Parameters.AddWithValue("@ID", ID); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } } } protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e) { if (Session["dt10"] != null) { dt10 = (DataTable)Session["dt10"]; } else { BindDatatable(); } DeleteAttachment(ID); DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"])); dt10.Rows.Remove(grdTrain[0]); AddToViewState("GrdTraining"); } ,我得到了ID

错误消息:

  

将数据类型nvarchar转换为数字

时出错

请建议一种调用动态ID的方法。

2 个答案:

答案 0 :(得分:1)

根据您的评论,我认为您需要执行以下操作

private void DeleteAttachment(string ID)
{
    decimal numericId;
    if(!decimal.TryParse(ID, out numericId))
    {
        // The ID is not a valid decimal determine what to do in that case.
    }

    using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
    {
        connection.Open();
        string sql = "DELETE FROM EMP_ATTACHED_DOCUMENTS WHERE mkey= @ID";
        using (SqlCommand cmd = new SqlCommand(sql, connection))
        {
            cmd.Parameters.Add("@ID", SqlDbType.Decimal).Value = numericId;
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
    }
}

或者,您可以将ID方法的DeleteAttachment参数更改为decimal,并在方法外部进行解析。

答案 1 :(得分:0)

在DeleteAttachment中的

我会简单地说:

decimal temp;
if (!Decimal.TryParse(ID, out temp)) { return; }