双击GridView更新无图片宝石记录时出现System.DBNull转Byte[]错误求助
解决“Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'”错误
嘿,我一眼就看出问题出在哪了——当你双击没有图片的宝石记录时,dataGridView1.CurrentRow.Cells[6].Value对应的是数据库里的DBNull值(毕竟你已经设置Image列允许为空了),但你直接把它强制转换成Byte[],这就触发了类型转换异常。
核心修复方案
修改你的dataGridView1_CellDoubleClick事件代码,先判断单元格值是否为DBNull,再做对应的处理:
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { S_Gems myForm = new S_Gems(); // 文本字段赋值(建议后续也加上DBNull判断,避免潜在错误) myForm.Stock_Type.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString(); myForm.txtstock_no.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString(); myForm.txtno_of_peices.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString(); myForm.txt_gems.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString(); myForm.txt_weight.Text = this.dataGridView1.CurrentRow.Cells[5].Value.ToString(); // 关键修改:先判断是否为DBNull,再处理图片 if (dataGridView1.CurrentRow.Cells[6].Value != DBNull.Value) { byte[] pic = (Byte[])dataGridView1.CurrentRow.Cells[6].Value; using (MemoryStream stream = new MemoryStream(pic)) { // 用using自动释放流资源 myForm.pb1.Image = Image.FromStream(stream); } } else { // 没有图片时清空图片控件 myForm.pb1.Image = null; } myForm.txt_cost.Text = this.dataGridView1.CurrentRow.Cells[7].Value.ToString(); // myForm.label11.Text = this.dataGridView1.CurrentRow.Cells[8].Value.ToString(); // myForm.label11.Text = this.dataGridView1.CurrentRow.Cells[9].Value.ToString(); myForm.ShowDialog(); }
额外优化建议
统一保存逻辑
你现在的保存代码分了两种INSERT语句,其实可以统一成带Image列的版本,当没有图片时把参数值设为DBNull.Value,这样代码更简洁易维护:private void btnsave_Click(object sender, EventArgs e) { try { conn.Close(); conn.Open(); // 统一使用包含Image列的INSERT语句 String query = "INSERT INTO Stock_Gems (Stock_Type,Stock_no,No_of_pieces,Gem_Type,Weight,Image,Cost,Create_Date,Update_Date,UserID) VALUES(@Stock_Type,@stock_no,@No_of_pieces,@Gem_Type,@Weight,@image,@Cost,@Created_Date,@Updated_Date,@User_Create)"; SqlCommand command = new SqlCommand(query, conn); // ... 其他参数赋值保持不变 ... // 处理图片参数 if (pb1.Image != null) { using (MemoryStream stream = new MemoryStream()) { pb1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] pic = stream.ToArray(); command.Parameters.Add("@image", SqlDbType.Binary).Value = pic; } } else { command.Parameters.Add("@image", SqlDbType.Binary).Value = DBNull.Value; } // ... 后续执行逻辑保持不变 ... } }避免潜在的空引用错误
处理GridView的文本单元格时,最好也加上DBNull判断,比如:myForm.Stock_Type.Text = dataGridView1.CurrentRow.Cells[1].Value != DBNull.Value ? dataGridView1.CurrentRow.Cells[1].Value.ToString() : string.Empty;这样可以防止某些字段为空时调用
ToString()抛出异常。
内容的提问来源于stack exchange,提问作者Mohamed Anver
相关产品推荐
相关产品推荐

