无图片无法保存SQL记录,报错‘object reference not set to an instance of an object’求助
问题排查与解决方案
错误根源
你遇到的空引用错误,核心问题是判断条件找错了对象:
pb1作为窗体上的PictureBox控件实例,只要你在设计时拖放了这个控件,它就不会是null,所以你的if(pb1 != null)判断永远会成立- 当没有图片时,真正为
null的是pb1.Image属性,此时执行pb1.Image.Save()就会触发“object reference not set to an instance of an object”错误
另外还有一个隐藏问题:如果没有图片,你没有给@image参数赋值,而SQL语句里要求这个参数存在,这也会导致执行出错。
修正后的代码
private void btnsave_Click(object sender, EventArgs e) { try { string commandText = "INSERT INTO Stock_Jewelry VALUES(@Stock_Type,@stock_no,@Quantity,@image)"; SqlCommand command = new SqlCommand(commandText, conn); // 绑定非图片参数 command.Parameters.Add("@Stock_Type", SqlDbType.VarChar).Value = Stock_Type.Text; command.Parameters.Add("@stock_no", SqlDbType.NVarChar).Value = txt_stock_no.Text; // 注意:Quantity是Int类型,要把文本转成int,避免类型错误 command.Parameters.Add("@Quantity", SqlDbType.Int).Value = int.Parse(txt_qty.Text); // 处理图片参数:判断Image是否为null if(pb1.Image != null) { using(MemoryStream stream = new MemoryStream()){ pb1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] pic = stream.ToArray(); command.Parameters.AddWithValue("@image", pic); } } else { // 没有图片时,给参数赋值DBNull.Value,对应数据库的NULL command.Parameters.AddWithValue("@image", DBNull.Value); } command.ExecuteNonQuery(); MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Hide(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
额外注意事项
- 确保数据库中
Stock_Jewelry表的image字段设置为允许NULL,否则即使传DBNull.Value也会报错 txt_qty.Text是字符串类型,直接转int可能会抛出格式错误,建议添加验证逻辑,比如用int.TryParse判断输入是否为有效数字:if(!int.TryParse(txt_qty.Text, out int qty)){ MessageBox.Show("Please enter a valid number for quantity!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } command.Parameters.Add("@Quantity", SqlDbType.Int).Value = qty;- 用
using语句包裹MemoryStream可以自动释放资源,避免内存泄漏
内容的提问来源于stack exchange,提问作者mms mms
相关产品推荐
相关产品推荐

