ExecuteNonQuery抛出invalidCastException

时间:2015-10-10 20:25:53

标签: c# sql sql-server

我只是想对数据库做一个简单的更新,我得到一个我不明白的例外。

以下是代码 - 请帮助:

protected void btnmodif_Click(object sender, EventArgs e)
{
   SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AGENDAConnectionString2"].ConnectionString );

   SqlCommand sqlComm = new SqlCommand();
   sqlComm = sqlConn.CreateCommand();

   sqlComm.CommandText = @"UPDATE RDV SET STATUES_COM = @STAT_COM WHERE INDICE = @ind";

   sqlComm.Parameters.Add("@STAT_COM", SqlDbType.VarChar);
   sqlComm.Parameters["@STAT_COM"].Value = DropDownList1.SelectedItem.Text;

   sqlComm.Parameters.Add("@ind", SqlDbType.VarChar);
   sqlComm.Parameters["@ind"].Value = Request.QueryString["Champ"].ToString();

   sqlConn.Open();
   sqlComm.ExecuteNonQuery();
   sqlConn.Close();

   Response.Write(@"<script language='javascript'>alert('SUCCESS');</script>");
}

我更新了代码

1 个答案:

答案 0 :(得分:1)

在按钮点击事件中用这个

替换你的代码
protected void btnmodif_Click(object sender, EventArgs e)
{
   var wasSuccessful = UpDateDB();
   if(wasSuccessful)
   {
      //Do Something 
   }
   else
   {
     //Do Something Else logging etc...
   }
}

public static bool UpDateDB()
{
    var ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AGENDAConnectionString2"].ConnectionString;
    bool successful = false;
    var ddlSelectedText = DropDownList1.SelectedItem.Text;
    var strUpdate = "UPDATE RDV SET STATUES_COM = @STAT_COM WHERE INDICE = @ind"; 

    using (SqlConnection connection = new SqlConnection(ConnString))
    {
        using (SqlCommand sqlComm = new SqlCommand(strUpdate, connection))
        {
            sqlComm.CommandType = CommandType.Text;
            sqlComm.Parameters.AddWithValue("@STAT_COM", ddlSelectedText);
            sqlComm.Parameters.AddWithValue("@ind", (string)Request.QueryString["Champ"]);
            sqlComm.CommandTimeout = 120;
            sqlComm.Connection.Open();
            try
            {
                sqlComm.ExecuteNonQuery();
                successful = true;
            }
            catch(SqlException SqlEx)
            {
                successful = false;
                //Write to a long SqlEx.Message
            }
        }
    }
    return successful;
}