sqlparametercollection只接受非null的sqlparameter类型对象而不是byte []对象

时间:2015-09-02 07:11:56

标签: c#

我有以下代码在运行时抛出异常:

  

sqlparametercollection只接受非null的sqlparameter类型对象而不是byte []对象

我不明白此错误在此方法中的确切位置:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        // error handling removed

        cc.cn = new SqlConnection(cs.DBconn);
        cc.cn.Open();
        string cb = "insert into UserRegistration(U_ID,UserId,Name,Address,City,ContactNo,Email,Photo) VALUES (@d1,@d2,@d3,@d4,@d5,@d6,@d7,@d8)";
        cc.cmd = new SqlCommand(cb);
        cc.cmd.Connection = cc.cn;
        cc.cmd.Parameters.AddWithValue("@d1", txtId.Text);
        cc.cmd.Parameters.AddWithValue("@d2", txtUserId.Text);
        cc.cmd.Parameters.AddWithValue("@d3", txtUserName.Text);
        cc.cmd.Parameters.AddWithValue("@d4", txtAddress.Text);
        cc.cmd.Parameters.AddWithValue("@d5", txtCity.Text);
        cc.cmd.Parameters.AddWithValue("@d6", txtContactNo.Text);
        cc.cmd.Parameters.AddWithValue("@d7", txtEmailId);
        MemoryStream ms = new MemoryStream();
        Bitmap bmpImage = new Bitmap(Picture.Image);
        bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] data = ms.GetBuffer();
        SqlParameter p = new SqlParameter("@d8", SqlDbType.Image);
        p.Value = data;
        cc.cmd.Parameters.Add(p.Value);
        cc.cmd.ExecuteReader();
        cc.cn.Close();
        st1 = lblId.Text;
        st2 = "added the new User'" + txtUserName.Text + "' having User id '" +txtUserId.Text + "'";
        cf.LogFunc(st1, System.DateTime.Now, st2);
        btnSave.Enabled = false;
        MessageBox.Show("Successfully saved", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

我应该改变什么才能得到错误?

2 个答案:

答案 0 :(得分:0)

您在代码blob中遇到了几个问题:

 cc.cmd.Parameters.AddWithValue("@d7", txtEmailId.Text); // use the Text property!

 SqlParameter p = new SqlParameter("@d8", SqlDbType.Image);
 p.Value = data;
 cc.cmd.Parameters.Add(p); // add the SqlParameter instance, not the byte[] array

并非严格需要,但由于您没有运行select语句,因此最好拨打ExecuteNonQuery而不是ExecuteReader

 int rowsChanged = cc.cmd.ExecuteNonQuery();

通过这些更改,您应该很好地解决这些错误。

答案 1 :(得分:0)

ExecuteReader()仅适用于SELECT次查询。你需要使用ExecuteNonQuery()